Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash: how to zip an array of objects with values

I'm looking how to zip an array of objects with values including a new key for each value using lodash. Tried with zip, zipObject and map but I don't find the key.

What I want to do is the following (avoiding to iterate manually over the arrays)

   const array = [
     {a: 3, b: 42}, 
     {c: 4}, 
     {d: 12}
   ]
   const values = ['these', 'are', 'new', 'values']

   // goal = foo(array, values) <<< HERE
   goal = [
     {a: 3, b: 42, v: 'these'}, 
     {c: 4, v: 'are'},
     {d: 12, v:'new'}
   ]
like image 302
Manu Avatar asked Mar 13 '23 21:03

Manu


1 Answers

You can use zipWith() to provide a custom iteratee:

var newArray = _.zipWith(array, values, function(item, value) {
    return _.defaults({ v: value }, item);
});

Note that this approach doesn't mutate the original array.

like image 132
Adam Boduch Avatar answered Mar 26 '23 22:03

Adam Boduch