Search code examples
javascriptdictionaryziplodash

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'}
   ]

Solution

  • 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.