lodash:如何压缩具有值的对象数组

Man*_*anu 6 javascript zip dictionary lodash

我正在研究如何使用 lodash 压缩具有值的对象数组,包括每个值的新键。尝试使用zipzipObjectmap但我没有找到密钥。

我想做的是以下(避免手动迭代数组)

   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'}
   ]
Run Code Online (Sandbox Code Playgroud)

Ada*_*uch 6

您可以使用zipWith()提供自定义迭代器:

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

请注意,这种方法不会改变原始的array.