使用array属性展平复杂对象的数组

时间:2019-06-28 12:15:57

标签: javascript arrays typescript object

我想知道是否有快速解决方案(例如使用map())将多维数组转换为一维数组,而该数组仍保留原始数组的所有信息。

您可以通过一些循环来解决它,但是我认为必须有一个更明智的解决方案。

为更多说明,这里是一个示例:

const arr = [{
  id: 1,
  people: [
    {name: "x", surname: "x"},
    {name: "y", surname: "y"}
  ]
 },{
  id: 2,
  people: [
    {name: "a", surname: "a"},
    {name: "b", surname: "b"}
  ]
 }]

const result = [
 {id: 1, name: "x", surname: "x"},
 {id: 1, name: "y", surname: "y"},
 {id: 2, name: "a", surname: "a"},
 {id: 2, name: "b", surname: "b"}
]

3 个答案:

答案 0 :(得分:2)

使用Array.flatMap()和内部Array.map()来添加id

const arr = [{"id":1,"people":[{"name":"x","surname":"x"},{"name":"y","surname":"y"}]},{"id":2,"people":[{"name":"a","surname":"a"},{"name":"b","surname":"b"}]}]
 
const result = arr.flatMap(({ id, people }) => people.map(p => ({ id, ...p })))

console.log(result)

如果目标浏览器不支持Array.flatMap(),请使用Array.map(),并传播到Array.concat()

const arr = [{"id":1,"people":[{"name":"x","surname":"x"},{"name":"y","surname":"y"}]},{"id":2,"people":[{"name":"a","surname":"a"},{"name":"b","surname":"b"}]}]
 
const result = [].concat(...arr.map(({ id, people }) => people.map(p => ({ id, ...p }))))

console.log(result)

答案 1 :(得分:1)

您可以尝试使用map()flat()

const arr = [{
  id: 1,
  people: [
    {name: "x", surname: "x"},
    {name: "y", surname: "y"}
  ]
 },{
  id: 2,
  people: [
    {name: "a", surname: "a"},
    {name: "b", surname: "b"}
  ]
 }]

const result = arr.map(p => {
  return p.people.map(pi => Object.assign(pi, {id: p.id}));
}).flat();
console.log(result);

答案 2 :(得分:1)

您可以使用array.reduce为每个people创建多个条目,假设数组从不改变其形式。 有关其工作原理的更多评论直接在代码中。

const arr = [{
  id: 1,
  people: [
    {name: "x", surname: "x"},
    {name: "y", surname: "y"}
  ]
 },{
  id: 2,
  people: [
    {name: "a", surname: "a"},
    {name: "b", surname: "b"}
  ]
 }]

// Reduce the origianal array.
const r = arr.reduce((acc, {id, people}) => {
  // For each people, push a new elemen to the array.
  return people.forEach(_people => {
    // the element pushed will hold the [id] and all the properties of the currently looped [people] item.
    acc.push(Object.assign({id}, _people));
  }), acc; // <-- finally, return the accumulator for the next iteration.
}, []); // <-- provide a new empty array as an initial value.
console.log(r);