lodash: how to zip an array of objects with values

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 12:04:33

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!