如何按键合并对象数组?

时间:2018-04-25 10:07:48

标签: javascript jquery loops

我有这个对象:

[{
  "NOMOR_CB": "CB/20-0718",
  "ITEM": "ABC"
}, {
  "NOMOR_CB": "CB/20-0719",
  "ITEM": "A1"
}, {
  "NOMOR_CB": "CB/20-0719",
  "ITEM": "A2"
}]

我要合并相同NOMOR_CB的值,以便合并相同NOMOR_CB的值。这是期望的输出。

[{
  "NOMOR_CB": "CB/20-0718",
  "ITEM": "ABC"
}, {
  "NOMOR_CB": "CB/20-0719",
  "ITEM": "A1, A2"
}]

如何循环对象以获得所需的输出?

我当前的循环(无法合并值):

var arr_test = "[";
$.each(response.arr_json, function(i, data) {
  arr_test += '{"NOMOR_CB":"'+ data.NOMOR_CB +'",';
  arr_test += '"ITEM":"'+ data.ITEM +'"},';
})

var test  = arr_test.replace(/,\s*$/, "");
test += "]";

document.write(test);

1 个答案:

答案 0 :(得分:0)

您可以使用.reduce()将数组汇总到一个对象中。使用Object.entries将对象转换为数组。您可以map形成所需的对象格式。

let arr = [{"NOMOR_CB":"CB/20-0718","ITEM":"ABC"},{"NOMOR_CB":"CB/20-0719","ITEM":"A1"},{"NOMOR_CB":"CB/20-0719","ITEM":"A2"}];

let result = Object.entries(arr.reduce((c, {NOMOR_CB,ITEM}) => {
  c[NOMOR_CB] = c[NOMOR_CB] || [];
  c[NOMOR_CB].push(ITEM);
  return c;
}, {})).map(([i, a]) => Object.assign({}, {NOMOR_CB: i,ITEM: a.join(', ')}));

let str = JSON.stringify(result); //Optional. Based on your code, you are trying to make a string.

console.log(str);

并且不要连接字符串以形成json。您可以使用JSON.stringify(result);将js对象转换为字符串。

文档:.reduce().map()