如何通过键合并对象数组? [英] How to merge an array of objects by key?

查看:79
本文介绍了如何通过键合并对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个对象:

[{
  "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的值.这是所需的输出.

I'd to merge the values of the same NOMOR_CB so the values of the same NOMOR_CB is combined. This is the desired output.

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

如何遍历对象以获得所需的输出?

How do I loop over the object to have the desired output?

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

My current loop (unable to combine the values):

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);

推荐答案

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

You can use .reduce() to summarise your array into an object. Use Object.entries to convert the object into an array. You can map to form the desired object format.

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对象转换为字符串.

And dont concatenate strings to form a json. You can use JSON.stringify(result); to convert js object to string.

文档: .reduce() .map()

这篇关于如何通过键合并对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆