如何在一个键/值对Javascript中添加几个相同的键对象数据?



我有这样的数据:

[{
"Key":"A",
"Data":"1"  
},
{
"Key":"B",
"Data":"2"  
},
{
"Key":"C",
"Data":"12" 
},
{
"Key":"A",
"Data":"6"  
},
{
"Key":"B",
"Data":"4"  
}]

我想要的输出是:

[
{
"Key":"A",
"Value":[{"Data":"1"},{"Data":"6"}]
},
{
"Key":"B",
"Value":[{"Data":"2"},{"Data":"4"}]
},
{
"Key":"C",
"Value":[{"Data":"12"}]
}
]

我希望在 Javascript 或 TypeScript 中动态地输出这样的输出,因为我得到了这个 json 数据动态.

有人可以帮忙吗?

您可以使用哈希表并按属性对项目进行分组Key

如果该组不存在,请使用 key 和Values数组创建一个新组。将新对象放入结果数组 10 个。稍后将实际值推送到Values数组。

var data = [{ Key: "A", Data: "1" }, { Key: "B", Data: "2" }, { Key: "C", Data: "12" }, { Key: "A", Data: "6" }, { Key: "B", Data: "4" }],
hash = Object.create(null),
result = data. reduce(function (r, o) {
if (!hash[o.Key]) {
hash[o.Key] = { Key: o.Key, Value: [] };
r.push(hash[o.Key]);
}
hash[o.Key].Value.push({ Data: o.Data });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

你可以这样做:

let data = [{
"Key":"A",
"Data":"1"  
},
{
"Key":"B",
"Data":"2"  
},
{
"Key":"C",
"Data":"12" 
},
{
"Key":"A",
"Data":"6"  
},
{
"Key":"B",
"Data":"4"  
}];
let groupedData = data.reduce((results, item) => {
results[item.Key] = results[item.Key] || [];
results[item.Key].push(item.Data);
return results;
}, {});
console.log(groupedData);

最新更新