Manu Artero
Manu Artero

Reputation: 10253

Populate Arrays using Lodash

Using lodash, how can I "populate" an array of keys using values from another array as following:

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'} }
   ];
 */

Actually, I'm iterating both arrays manually, but I cannot figured out how can it be done with Lodash.

Upvotes: 0

Views: 1957

Answers (2)

Abhinash Sharma
Abhinash Sharma

Reputation: 27

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

Upvotes: 0

Maurits Rijk
Maurits Rijk

Reputation: 9985

Assuming the keys and refs are unique:

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

Short explanation: the first line creates a lookup hash for efficiency reasons. The second line merges every object in your array with an item in the lookup hash that matches the value of ref with key.

Upvotes: 3

Related Questions