繁体   English   中英

如何转置 TypeScript 中的对象数组?

[英]How to transpose array of objects in TypeScript?

我有一个对象数组,如下所示:

finalList = [
  [{name: john}, {name: max}, {name: rob}],
  [{id: 1}, {id: 2}, {id: 3}],
  [{gender: M}, {gender: F}, {gender: M}],
]

我需要数组像这样转置:

finalList = [ 
  {name: john, id: 1, gender: M},
  {name: john, id: 1, gender: M},
  {name: john, id: 1, gender: M}
]

object 的实际数组在嵌套数组中。 请帮助我指导转置 TypeScript 中的数组。

这是一个很好的功能方式。 它假定finalList中的每个数组都具有相同的长度和相同的键(因此没有错误处理)。

 const finalList = [ [{name: "john"}, {name: "max"}, {name: "rob"}], [{id: 1}, {id: 2}, {id: 3}], [{gender: "M"}, {gender: "F"}, {gender: "M"}], ]; console.log(finalList); // this is a trick to create an array of a specific size with unique objects inside it // the fill is necessary to iterate over the holed array (https://stackoverflow.com/q/40297442/2178159) // fill({}) won't work since it's a single object ref that will be shared const results = new Array(finalList.length).fill(null).map(() => ({})); finalList.forEach(group => { group.forEach((obj, i) => { Object.assign(results[i], obj); }) }); console.log(results);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM