var dictA = { male: 10, female: 20, unassigned: 30 };
var dictB = { male: 11, female: 21, unassigned: 31 };
var dictC = { male: 12, female: 22, unassigned: 32 };


是否有比多个循环更简单的方法来产生如下结果:

{
    male: [10, 11, 12],
    female: [20, 21, 22],
    unassigned: [30, 31, 32]
}


我不确定'combine'在这里是否正确。

最佳答案

这仍然需要几个循环,但也许reducefor...in的组合将雄辩地完成此操作:



var dictA = { male: 10, female: 20, unassigned: 30 };
var dictB = { male: 11, female: 21, unassigned: 31 };
var dictC = { male: 12, female: 22, unassigned: 32 };

const res = [dictA, dictB, dictC].reduce((acc, el) => {
  for (let key in el) {
    acc[key] = [...acc[key] || [], el[key]];
  };
  return acc;
}, {})

console.log(res);

10-06 08:03