gpt4 book ai didi

javascript - JS (ES6) : Merge arrays based on id and concatenating sub arrays

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

我有两个数组,如下所示:

const persons = [
{
id: 1,
name: 'Peter',
job: 'Programmer'
},
{
id: 2,
name: 'Jeff',
job: 'Architect'
},
];

const salaries = [
{
id: 1,
salary: 3000,
departments: ['A', 'B']
},
{
id: 1,
salary: 4000,
departments: ['A', 'C']
},
{
id: 2,
salary: 4000,
departments: ['C', 'D']
}
];

现在我需要以某种方式将这些数组合并为一个,这样每个 id 只存在一次。应该替换相同的键,除了它是一个数组,然后我希望它们添加/连接。所以期望的结果应该是这样的:

const result = [
{
id: 1,
name: 'Peter',
job: 'Programmer',
salary: 4000,
departments: ['A', 'B', 'C']
},
{
id: 2,
name: 'Jeff',
job: 'Architect',
salary: 4000,
departments: ['C', 'D']
}
];

我已经试过了:

// double id's, arrays get replaced
Object.assign({}, persons, salaries)

// loadsh: double id's, arrays get concatenated
_.mergeWith(persons, salaries, (objValue, srcValue) => {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
});

// gives me a map but replaces arrays
new Map(salaries.map(x => [x.id, x])

有人知道如何实现吗?

最佳答案

您可以使用 map() , filter() , reduce() , Object.assign()Spread syntax达到要求的结果。

演示

const persons = [{
id: 1,
name: 'Peter',
job: 'Programmer'
}, {
id: 2,
name: 'Jeff',
job: 'Architect'
}],
salaries = [{
id: 1,
salary: 3000,
departments: ['A', 'B']
}, {
id: 1,
salary: 4000,
departments: ['A', 'C']
}, {
id: 2,
salary: 4000,
departments: ['C', 'D']
}];


let output = persons.map(obj => {
let filter = salaries.filter(v => v.id == obj.id);
if (filter) {
let departments = filter.reduce((r, v) => [...v.departments, ...r], []);
Object.assign(obj, {
salary: filter[filter.length - 1].salary,
departments: departments.filter((item, pos) => departments.indexOf(item) == pos).sort()
});
}
return obj;
});

console.log(output)

关于javascript - JS (ES6) : Merge arrays based on id and concatenating sub arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49649360/

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