gpt4 book ai didi

javascript - 如何从在 javascript 中具有相同键的对象创建对象数组

转载 作者:行者123 更新时间:2023-11-30 07:14:21 25 4
gpt4 key购买 nike

我有一个看起来像这样的对象数组

[{
"name": "Agile Process",
"id": 27,
"score": 3,
"source": "Self"
},{
"name": "Agile Process",
"id": 27,
"score": 4,
"source": "Trainer"
},{
"name": "2 & 3 Tier Architecture",
"id": 37,
"score": 4,
"source": "Self"
},{
"name": "2 & 3 Tier Architecture",
"id": 37,
"score": 5,
"source": "Trainer"
}]

我想做这样的东西,我一直在努力,但我似乎没有掌握它。

[
{
"name": "Agile Process",
"id": 7,
"data": [
{
"score": 3,
"source": "Self"
},{
"score": 4,
"source": "Trainer"
}
]
},
{
"name": "2 & 3 Tier Architecture",
"id": 37,
"data": [
{
"score": 4,
"source": "Self"
},{
"score": 5,
"source": "Trainer"
}]
}
];

我该如何解决这个问题?

最佳答案

一种可能的方法:

_.values(_.reduce(arr, function(acc, el) {
var id = el.id;
if (!acc.hasOwnProperty(id)) {
acc[id] = _.pick(el, 'id', 'name');
acc[id].data = [];
}
acc[id].data.push(_.pick(el, 'score', 'source'));
return acc;
}, {}));

Demo .当您需要对事物进行分组时,这是一种常用方法。

关于javascript - 如何从在 javascript 中具有相同键的对象创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com