gpt4 book ai didi

javascript - 使用 Lodash 填充数组

转载 作者:行者123 更新时间:2023-11-28 18:42:41 25 4
gpt4 key购买 nike

使用lodash ,如何使用另一个数组中的值“填充”键数组,如下所示:

let array = [{ obj: myObject, val: 42, ref: 4 }, { val: 100, ref: 1 }];
let refs = [{ key: 4, msg: 'Hello' }, { key: 1, msg: 'there' }]
// populate array[i].ref with refs[i].key
response = populate(array, refs, {key: 'ref', foreingKey: 'key'})

/*
response = [
{ obj: myObject, val: 42, ref: { key: 4, msg: 'Hello'} },
{ val: 100, ref: {key: 1, msg: 'There'} }
];
*/

实际上,我正在手动迭代两个数组,但我不知道如何使用 Lodash 来完成它。

最佳答案

假设键和引用是唯一的:

const lookup = _.keyBy(refs, 'key');
const response = _.map(array, x => _.merge(x, {ref: lookup[x.ref]}));

简短说明:出于效率原因,第一行创建一个查找哈希。第二行将数组中的每个对象与查找哈希中与 ref 的值与键匹配的项目合并。

关于javascript - 使用 Lodash 填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35887813/

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