2016-03-09 120 views
0

使用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如何做到這一點。

+0

請問ref = key,還是隻是從其他數組中的對應索引添加對象?如果前者,你的預期產出是錯誤的。 – Andy

回答

3

假設密鑰參是獨特的:

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

簡短說明:第一行創建出於效率的考慮一查找散。第二行將數組中的每個對象與查找哈希中與ref與key的值相匹配的項合併。