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)
var array = [
{a: 3, b: 42},
{c: 4},
{d: 12}
]
var values = ['this', 'are', 'new', 'values']
var goal = [
{a: 3, b: 42, v: 'this'},
{c: 4, v: 'are'},
{d: 12, v:'new'}
]
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.
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>
来源:https://stackoverflow.com/questions/34309220/lodash-how-to-zip-an-array-of-objects-with-values