简体   繁体   English

lodash:如何使用值压缩对象数组

[英]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. 我正在寻找如何使用lodash压缩包含值的对象数组,其中包括每个值的新键。 Tried with zip , zipObject and map but I don't find the key. 尝试使用zipzipObjectmap,但找不到密钥。

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: 您可以使用zipWith()提供自定义iteratee:

var newArray = _.zipWith(array, values, function(item, value) {
    return _.defaults({ v: value }, item);
});

Note that this approach doesn't mutate the original array . 注意,这种方法不会改变原始array

You can use the native map function. 您可以使用本机map功能。 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) {...}); 如果要使用lodash来执行此操作,则可以使用_.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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM