我正在研究如何使用 lodash 压缩具有值的对象数组,包括每个值的新键。尝试过zip https://lodash.com/docs#zip, zip对象 https://lodash.com/docs#zipObject and map https://lodash.com/docs#map但我没有找到钥匙。
我想做的是以下(避免手动迭代数组)
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'}
]
您可以使用zipWith() https://lodash.com/docs#zipWith提供自定义 iteratee:
var newArray = _.zipWith(array, values, function(item, value) {
return _.defaults({ v: value }, item);
});
请注意,这种方法doesn't改变原来的array
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)