gpt4 book ai didi

javascript - 如何根据lodash中每个数组的不同属性从2个数组返回1个数组?

转载 作者:行者123 更新时间:2023-12-01 00:30:52 24 4
gpt4 key购买 nike

Lodash v 4.17.15

假设我有 2 个数组

var users = [{
id: 12,
name: Adam
},{
id: 14,
name: Bob
},{
id: 16,
name: Charlie
},{
id: 18,
name: David
}
]


var jobs = [{
empid: 12,
profession: Engineer
},{
empid: 14,
profession: CEO
},{
empid: 16,
profession: CFO
},{
empid: 18,
profession: CTO
}
]

预期结果

var jobsEmp= [{
empid: 12,
id: 12,
name: Adam
profession: Engineer
},{
empid: 14,
id: 14,
name: Bob
profession: CEO
},{
empid: 16,
id: 16,
name: Charlie
profession: CFO
},{
empid: 18,
id: 18,
name: David
profession: CTO
}
]

我通常这样做:

var jobsEmp =  _.forEach(users, function (emp) {
emp.jobs = _.find(jobs, function (jb) {
return jb.empid === emp.id;
});
});

但我注意到这不是最好的方法,我已经阅读文档很长一段时间了,但我只是不知道什么技术是最好的,如何在lodash中正确地做到这一点?

最佳答案

你可以这样做,但在我看来,无论怎样让它对你和你的团队来说更具可读性。我更喜欢具有更高可读性的方法

const _ = require('lodash')

const users = [{
id: 12,
name: 'Adam'
},{
id: 14,
name: 'Bob'
},{
id: 16,
name: 'Charlie'
},{
id: 18,
name: 'David'
}
]


const jobs = [{
empid: 12,
profession: 'Engineer'
},{
empid: 14,
profession: 'CEO'
},{
empid: 16,
profession: 'CFO'
},{
empid: 18,
profession: 'CTO'
}
]

const merged = _.merge(_.keyBy(users, 'id'), _.keyBy(jobs, 'empid'));
const values = _.values(merged);
console.log(values);

输出

[ { id: 12, name: 'Adam', empid: 12, profession: 'Engineer' },
{ id: 14, name: 'Bob', empid: 14, profession: 'CEO' },
{ id: 16, name: 'Charlie', empid: 16, profession: 'CFO' },
{ id: 18, name: 'David', empid: 18, profession: 'CTO' } ]

关于javascript - 如何根据lodash中每个数组的不同属性从2个数组返回1个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58552088/

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