6

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

> this approach doesn't mutate the original array :thumbsup:
4

You can use the native map function. See the below snippet.

If you want to use lodash to do this, you can just do the same thing except with _.map(array, function (item, index) {...});.

var array = [
  {a: 3, b: 42}, 
  {c: 4}, 
  {d: 12}
];
var values = ['this', 'are', 'new', 'values']
 
var goal = array.map(function (item, index) {
  item.v = values[index];
  return item;
});

document.getElementById('goal').innerHTML = JSON.stringify(goal);
<div id="goal"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.