如何使用相同的键合并对象数组

时间:2019-01-01 07:00:41

标签: javascript

我有一个带有多个对象的数组,想通过相同的键合并它们而不会丢失其值。

我尝试了stakoverflow中的一些答案,但是它们都没有帮助我。我想通过map / reduce做到这一点,但是我不知道如何检索每个对象的键名来对其进行检查。

let rows = [
  { row1: [{ val: "row1-val1" }, { val: "row1-val2" }] },
  { row1: [{ val: "row1-val3" }, { val: "row1-val4" }] },
  { row1: [{ val: "row1-val5" }, { val: "row1-val6" }] },
  { parag: { text: "sample test" } },
  { row2: [{ val: "row2-val1" }, { val: "row2-val2" }] },
  { row2: [{ val: "row2-val3" }, { val: "row2-val4" }] },
  { row2: [{ val: "row2-val5" }, { val: "row2-val6" }] }
];

我想要这个结果:

let rows = [
  {
    row1: [
      { val: "row1-val1" },
      { val: "row1-val2" },
      { val: "row1-val3" },
      { val: "row1-val4" },
      { val: "row1-val5" },
      { val: "row1-val6" }
    ]
  },
  { parag: { text: "sample test" } },
  {
    row2: [
      { val: "row2-val1" },
      { val: "row2-val2" },
      { val: "row2-val3" },
      { val: "row2-val4" },
      { val: "row2-val5" },
      { val: "row2-val6" }
    ]
  }
];

1 个答案:

答案 0 :(得分:1)

您可以在reduce的帮助下完成

let rows = [{ row1: [{ val: "row1-val1" }, { val: "row1-val2" }] },{ row1: [{ val: "row1-val3" }, { val: "row1-val4" }] },{ row1: [{ val: "row1-val5" }, { val: "row1-val6" }] },{ parag: { text: "sample test" } },{ row2: [{ val: "row2-val1" }, { val: "row2-val2" }] },{ row2: [{ val: "row2-val3" }, { val: "row2-val4" }] },{ row2: [{ val: "row2-val5" }, { val: "row2-val6" }] }];

let op = rows.reduce((o,c)=>{
  let key = Object.keys(c)[0];
  if(o[key]){
    o[key].push(...c[key]);
  } else {
    o[key] = c[key];
  }
  return o;
},{})

console.log(op)