使用 Lodash 填充数组
Populate Arrays using Lodash
使用 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 的值与键匹配的项目合并。
const temp = [];
let array = [
{ obj: myObject, val: 42, ref: 4 },
{ val: 100, ref: 1 }
];
let refs = [
{ key: 4, msg: 'Hello' },
{ key: 1, msg: 'there' }
];
array.forEach(x =>{
refs.forEach(y => {
if (x.refs === y.key) {
temp.push({ ...x, ...y })
}
})
})
使用 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 的值与键匹配的项目合并。
const temp = [];
let array = [
{ obj: myObject, val: 42, ref: 4 },
{ val: 100, ref: 1 }
];
let refs = [
{ key: 4, msg: 'Hello' },
{ key: 1, msg: 'there' }
];
array.forEach(x =>{
refs.forEach(y => {
if (x.refs === y.key) {
temp.push({ ...x, ...y })
}
})
})