lodash: how to zip an array of objects with values

谁说胖子不能爱 提交于 2019-12-22 17:06:43

问题


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

回答1:


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.




回答2:


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

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