【问题标题】:How to transpose array of objects in TypeScript?如何在 TypeScript 中转置对象数组?
【发布时间】:2020-07-16 11:08:52
【问题描述】:

我有一个如下的对象数组:

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}
]

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

【问题讨论】:

  • 到目前为止你尝试过什么?您应该清楚地说明您的要求和预期的输出。不清楚为什么finalList 中有 3 个重复对象。
  • 没有内置命令可以做到这一点。应该手动完成。

标签: html arrays angular typescript


【解决方案1】:

这是一个很好的实用方法。它假定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);

【讨论】:

  • 谢谢。但我收到如下错误。 Cannot convert undefined or null to objectconst results = new Array(this.finalList.length).fill(null).map(() => ({})); this.finalList.forEach(group => { group.forEach((obj: any, i: string | number) => { Object.assign(results[i], obj); }); }); console.log(results);
  • 您发布的代码似乎没问题,但可能是 this.finalList 没有被正确引用。见stackoverflow.com/a/29721434/2178159
猜你喜欢
  • 1970-01-01
  • 2021-11-20
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
相关资源
最近更新 更多