javascript-如何使用lodash在对象数组中合并/连接相同对象属性的值?
作者:互联网
我有一个对象数组,看起来像这样:
let fruitSamples = [
[
{'id': 1,'type': 'apples','samples': [1, 2, 3]},
{'id': 2,'type': 'bananas','samples': [1, 2, 7]},
{'id': 3,'type': 'pears','samples': [1, 2, 3]}
],
[
{'id': 1,'type': 'apples','samples': [5, 2, 9]},
{'id': 2,'type': 'bananas','samples': [1, 7, 7]},
{'id': 3,'type': 'pears','samples': [12, 21, 32]}
],
[
{'id': 1,'type': 'apples','samples': [11, 2, 33]},
{'id': 2,'type': 'bananas','samples': [17, 2, 67]},
{'id': 3,'type': 'pears','samples': [91, 22, 34]}
]
];
我想使用lodash将上面的数组减少并合并为一个数组,以便将样本连接在一起,如下所示:
fruitSamples = [
{'id': 1, 'type': 'apples', 'samples': [1,2,3,5,2,9,11,2,33]},
{'id': 2, 'type': 'bananas', 'samples': [1,2,7,1,7,7,17,2,67]},
{'id': 3, 'type': 'pears', 'samples': [1,2,3,12,21,32,91,22,34]},
]
我尝试了许多不同的方法,但是由于我想要最短的解决方法,您的建议是什么?
我已经试过了:
let test = _(fruitSamples)
.flatten()
.groupBy('type')
.map(_.spread(_.merge))
.value();
console.log(test);
这给了我以下结果,该结果未连接样本:
test = [
{'id': 1,'type': 'apples','samples': [11, 2, 33]},
{'id': 2,'type': 'bananas','samples': [17, 2, 67]},
{'id': 3,'type': 'pears','samples': [91, 22, 34]}
]
我觉得使用_.mergeWith可能是正确的答案,如果是这样,我正在寻求以最佳方式实现mergeWith的帮助,因为我不确定该怎么做.有什么建议么?
解决方法:
您可以尝试使用_.mergeWith
而不是_.merge来接受定制器功能,该功能可用于定制分配的值.
This method is like
_.merge
except that it accepts customizer which is
invoked to produce the merged values of the destination and source
properties.
let fruitSamples = [
[
{'id': 1,'type': 'apples','samples': [1, 2, 3]},
{'id': 2,'type': 'bananas','samples': [1, 2, 7]},
{'id': 3,'type': 'pears','samples': [1, 2, 3]}
],
[
{'id': 1,'type': 'apples','samples': [5, 2, 9]},
{'id': 2,'type': 'bananas','samples': [1, 7, 7]},
{'id': 3,'type': 'pears','samples': [12, 21, 32]}
],
[
{'id': 1,'type': 'apples','samples': [11, 2, 33]},
{'id': 2,'type': 'bananas','samples': [17, 2, 67]},
{'id': 3,'type': 'pears','samples': [91, 22, 34]}
]
];
function customizer(objValue, srcValue) {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
}
let test = _(fruitSamples)
.flatten()
.groupBy('type')
.map(_.spread((...values) => {
return _.mergeWith(...values, customizer);
}))
.value();
console.log(test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
标签:javascript-objects,lodash,arrays,javascript 来源: https://codeday.me/bug/20191108/2007185.html