JS:根据特定键的值重新组织数组中的对象(r​​educe?)

时间:2014-04-13 21:30:50

标签: javascript arrays grouping aggregate reduce

这是this one的后续问题,虽然两者在运作方面无关


从这种结构开始:

[ [{ field: "field1", term: "val1"},
   { field: "field2", term: "val2"}
  ],
  [{ field: "field3", term: "val3"},
   { field: "field3", term: "val4"},
   { field: "field4", term: "val5"}
  ],
  [{ field: "field3", term: "val6"},
   { field: "field2", term: "val7"},
   { field: "field3", term: "val8"},
   { field: "field1", term: "val9"},
   { field: "field2", term: "val10"}
  ]
]

我需要迭代每个子数组,并且对于内部的每个对象,当键term相同时,将键field的值聚合到一个数组中;为了简单起见,通过相同的场合将键term的所有值包装在一个数组中。最终结果如下:

[ [{ field: "field1", term: ["val1"]},
   { field: "field2", term: ["val2"]}
  ],
  [{ field: "field3", term: ["val3", "val4"},
   { field: "field4", term: ["val5"]}
  ],
  [{ field: "field3", term: ["val6", "val8"]},
   { field: "field2", term: ["val7", "val10"]},
   { field: "field1", term: ["val9"]}
  ]
]

我尝试过为每个物品玩_.reduce,相对接近但从未完全存在过。根本没有掌握这种模式,我不相信reduce是要走的路

任何想法或指示?试图把这个包裹2天......:S

由于

1 个答案:

答案 0 :(得分:2)

好吧,你可以为每个数组创建一个新的对象" field"值作为键," term"数组作为值。然后,您可以将其转换回原始形式的对象。

var newArray = array.map(function( subArray ) {
  var obj = subArray.reduce(function(m, o) {
    if (o.field in m)
      m[o.field].push(o.term);
    else
      m[o.field] = [o.term];
    return m;
  }, {});

  return Object.keys(obj).map(function(field) {
    return { field: field, term: obj[field] };
  });
});