【发布时间】:2018-09-13 22:02:24
【问题描述】:
我有两个数组,如下所示:
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])
有谁知道如何做到这一点?
【问题讨论】:
-
我会给你一个提示,根据 id 对两个数组进行排序,然后尝试比较 em
-
理解应该拿哪个薪水的逻辑是什么?最新的?薪水最高?
-
@MiguelAngel 最新的
标签: javascript arrays merge ecmascript-6 array-merge