如何展平包含数组的对象数组?

时间:2019-05-02 09:23:43

标签: javascript arrays object ecmascript-6

我想将项目展平为一个对象数组并接收一个新的结果数组。我该如何实现?

这种方法行不通:

const group = [{
    idGroup: 1,
    member: [{
      name: "Tim"
    }, {
      name: "Sina"
    }]
  }],
}];

const result = [{
    idGroup: 1,
    name: "Tim"
  },
  {
    idGroup: 1,
    name: "Sina"
  },
]



const result = group.reduce((r, obj) => r.concat(obj.member), []);

console.log(result)

5 个答案:

答案 0 :(得分:2)

您可以映射嵌套对象。

const
    group = [{ idGroup:1, member: [{ name: "Tim" }, { name: "Sina" }] }];
    result = group.reduce(
        (r, { idGroup, member }) => [...r, ...member.map(({ name }) => ({ idGroup, name }))],
        []
    );

console.log(result);

或使用即将推出的Array#flatMap

const
    group = [{ idGroup:1, member: [{ name: "Tim" }, { name: "Sina" }] }];
    result = group.flatMap(({ idGroup, member }) =>
        member.map(({ name }) => ({ idGroup, name })));

console.log(result);

答案 1 :(得分:2)

您可以在对象flatMap()的数组上使用map()member

const group = [
 {
  idGroup:1,
  member: [{name: "Tim"}, {name: "Sina"}],
 }
];

const res = group.flatMap(x => x.member.map(a => ({...a,idGroup:x.idGroup})));
console.log(res)

答案 2 :(得分:1)

您还需要使用map(制作新商品):

const group = [{idGroup:1,member:[{name: "Tim"},{name: "Sina"}]}];
const result = group.reduce((acc, { idGroup, member }) => acc.concat(member.map(({ ...props }) => ({ ...props, idGroup }), [])), []);
console.log(result);

答案 3 :(得分:1)

您可以像这样使用Array.prototype.reduce()Array.prototype.forEach()

const group = [{
  idGroup: 1,
  member: [{name: "Tim"}, {name: "Sina"}],
}, {
  idGroup: 2,
  member: [{name: "Jo"}, {name: "Eric"}]
}];

const result = group.reduce((acc, { idGroup, member }) => {
  member.forEach(({ name }) => acc.push({ idGroup, name }));
  return acc;
}, []);

console.log(result);

答案 4 :(得分:1)

良好的旧循环也可以工作。

const group =
[{
    idGroup: 1,
    member: [{
      name: "Tim"
    }, {
      name: "Sina"
    }]
},
{
    idGroup: 2,
    member: [{
      name: "foo"
    }, {
      name: "bar"
    }, {
      name: "42"
    }]
}];

let result = [];

group.forEach((elem) => {
  elem.member.forEach((subElem) => {
    result.push({ idGroup: elem.idGroup, name: subElem.name });
  });
});

console.log(result);