gpt4 book ai didi

javascript - 我想合并数组中的值(如果它们具有相同的 id)

转载 作者:行者123 更新时间:2023-11-28 17:01:41 25 4
gpt4 key购买 nike

我有一个数组对象,它具有相同的 Id 和不同的值。我需要一个具有相同 id 和合并到 id 的不同值的输出。

输入:

let data = [{
id: 1,
value: 'Honda'
},
{
id: 2,
value: 'Fiat'
},
{
id: 2,
value: 'Porche'
},
{
id: 1,
value: 'Benz'
}
];

输出:

result = [{
id: 1,
value: ['Honda', 'Benz']
}, {
id: 2,
value: ['Fiat', 'Porche']
}

最佳答案

希望对您有帮助。但这个问题是重复的

let data = [{
id: 1,
value: 'Honda'
},
{
id: 2,
value: 'Fiat'
},
{
id: 2,
value: 'Porche'
},
{
id: 1,
value: 'Benz'
}
];

var output = [];

data.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.id == item.id;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].value = output[existingIndex].value.concat(item.value);
} else {
if (typeof item.value == 'string')
item.value = [item.value];
output.push(item);
}
});

console.dir(output);

关于javascript - 我想合并数组中的值(如果它们具有相同的 id),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57253083/

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