我有一个数组对象,它具有相同的 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/