Javascript,将多个词典合并为一个词典

时间:2020-09-08 13:44:17

标签: javascript

我有一个for循环,该循环生成具有多个键和每个键一个值的字典。

{AdvanceAxes: "NaN", AnalSect: "Rigid_Conc", Angle: NaN, AutoSelect: "N.A.", CaseType: "Combination", …}

我想将这些词典合并为一个词典。以一种方式在每次迭代时追加到字典 最终结果将是一个数组字典,其键与每次迭代中出现的字典具有相同的键。 像这样:

{AdvanceAxes: Array(9168), AnalSect: Array(9168), Angle: o(9168), AutoSelect: Array(9168), CaseType: Array(9168), …}

到目前为止,我失败了。有没有办法用Javascript实现呢?

1 个答案:

答案 0 :(得分:0)

您可以像这样使用reduce

let data = [
    {AdvanceAxes: "NaN", AnalSect: "Rigid_Conc", Angle: NaN, AutoSelect: "N.A.", CaseType: "Combination"},
    {AdvanceAxes: "NaN", AnalSect: "Rigid_Conc", Angle: NaN, AutoSelect: "N.A.", CaseType: "Combination"},
    {AdvanceAxes: "NaN", AnalSect: "Rigid_Conc", Angle: NaN, AutoSelect: "N.A.", CaseType: "Combination"},
];

// iterate data array and use empty object "a" as accumulator
let dict = data.reduce((a, e) => 
  // iterate each object entry as [key, value] and use "a" as accumulator
  Object.entries(e).reduce((a, t) => {
      // create an empty array on "a" for each key (if it does not exist yet)
      // then push current value to it
      (a[t[0]] = a[t[0]] || []).push(t[1]);
      return a;
  }, a), {});

console.log(dict);