我有两个数组,如下所示:
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/