,可以通过以下步骤实现:
下面是一个示例代码,演示了如何按id合并数组并考虑具有重复关联索引的唯一值:
function mergeArrays(arr) {
const groups = {};
// 分组
arr.forEach(item => {
if (!groups[item.id]) {
groups[item.id] = [];
}
groups[item.id].push(item);
});
const mergedArray = [];
// 合并数组
for (const id in groups) {
const group = groups[id];
const mergedItem = { id };
for (const item of group) {
for (const key in item) {
if (key !== 'id') {
if (!mergedItem[key]) {
mergedItem[key] = new Set();
}
mergedItem[key].add(item[key]);
}
}
}
// 将Set转换为数组
for (const key in mergedItem) {
if (key !== 'id') {
mergedItem[key] = Array.from(mergedItem[key]);
}
}
mergedArray.push(mergedItem);
}
return mergedArray;
}
// 示例数据
const arr = [
{ id: 1, name: 'A', value: 'X' },
{ id: 2, name: 'B', value: 'Y' },
{ id: 1, name: 'C', value: 'Z' },
{ id: 2, name: 'D', value: 'W' }
];
const merged = mergeArrays(arr);
console.log(merged);
以上代码将输出以下结果:
[
{ id: 1, name: ['A', 'C'], value: ['X', 'Z'] },
{ id: 2, name: ['B', 'D'], value: ['Y', 'W'] }
]
这个结果表示按id合并数组,并将具有重复关联索引的属性值合并为唯一值的数组。在这个例子中,id为1的元素合并了name属性值为'A'和'C',value属性值为'X'和'Z'。id为2的元素合并了name属性值为'B'和'D',value属性值为'Y'和'W'。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云