需要帮助从深层阵列中提取对象并将其合并为一个阵列

时间:2018-08-22 21:31:37

标签: javascript node.js

提取具有target属性的对象并将它们组合成一个数组的最佳方法是什么?

app.js

const p1 = [[{ target1: 3 }, { target2: 1 }], [{ t: 2 }]];
const p2 = [[{ target1: 1 }, { target2: 2 }], [{ t: 2 }]];
const p3 = [[{ target1: 4 }, { target2: 1 }], [{ t: 2 }]];
const p4 = [[{ target1: 2 }, { target2: 2 }], [{ t: 2 }]];


Promise.all([p1, p2, p3, p4]).then((values) => {
    console.log(values);
    // Some way to extract the objects that have the target property in them 
    // and combine them into a single array
});

结果

[ [ [ [Object], [Object] ], [ [Object] ] ],
  [ [ [Object], [Object] ], [ [Object] ] ],
  [ [ [Object], [Object] ], [ [Object] ] ],
  [ [ [Object], [Object] ], [ [Object] ] ] ]

所需

[{ target1: 3 }, { target2: 1 },
{ target1: 1 }, { target2: 2 },
{ target1: 4 }, { target2: 1 },
{ target1: 2 }, { target2: 2 }]

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码实现目标。

const p1 = [[{ target1: 3 }, { target2: 1 }], [{ t: 2 }]];
const p2 = [[{ target1: 1 }, { target2: 2 }], [{ t: 2 }]];
const p3 = [[{ target1: 4 }, { target2: 1 }], [{ t: 2 }]];
const p4 = [[{ target1: 2 }, { target2: 2 }], [{ t: 2 }]];

Promise.all([p1, p2, p3, p4]).then((values) => {
   const [a1, a2, a3, a4] = values

   const [t1] = a1;
   const [t2] = a2;
   const [t3] = a3;
   const [t4] = a4;

   const result = [...t1, ...t2, ...t3, ...t4];

   console.log(result);
});

答案 1 :(得分:0)

尝试在数组上映射并使用解构方法:

let transformedValues = Array.prototype.concat( //poor man's one level flatten when combined with ...
  ...values.map(([[target1, target2]])=> [target1, target2])
)

我假设p值的数量有所不同,但是p值的结构是恒定的。