使用 Lodash 填充数组

Populate Arrays using Lodash

本文关键字:数组 填充 Lodash 使用      更新时间:2023-09-26

使用 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 }) 
    } 
  }) 
})