我正在尝试找到一种有效的方式来聚合集合中的所有项目。
例如,如果值不是子对象或数组,那么Lodash最有效的方法是通过每个键(深度)对这个对象集合进行分组?
let input = [{
food: {
fruits: {
apples: 2,
bananas: 3,
peaches: 'square',
citrus: [100,200,300]
},
meat: {
beef: 1000,
chicken: 2000
}
}
},{
food: {
fruits: {
apples: 4,
bananas: 5,
peaches: 'triangle',
citrus: [101,201,301]
},
meat: {
beef: 1001,
chicken: 2001
}
}
}];
let output = {
food: {
fruits: {
apples: [2,4],
bananas: [3,5],
peaches: ['square', 'triangle'],
citrus: [[100,101],[200,201],[300,301]]
},
meat: {
beef: [1000, 1001],
chicken: [2000, 2001]
}
}
}
似乎没有一个函数在API中执行它,我想知道是否有一种方法可以在一次传递中执行此操作而无需在初始集合上多次迭代。
答案 0 :(得分:1)
您可以按如下方式使用mergeWith()
:
const input = [{
food: {
fruits: {
apples: 2,
bananas: 3,
peaches: 'square',
citrus: [100, 200, 300]
},
meat: {
beef: 1000,
chicken: 2000
}
}
}, {
food: {
fruits: {
apples: 4,
bananas: 5,
peaches: 'triangle',
citrus: [101, 201, 301]
},
meat: {
beef: 1001,
chicken: 2001
}
}
}];
const output = _.mergeWith({}, ...input, (t, s) => {
if (!_.isObject(s)) return t ? [...t, s] : [s]
});
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
&#13;
{
"food": {
"fruits": {
"apples": [2, 4],
"bananas": [3, 5],
"peaches": ["square", "triangle"],
"citrus": [[100, 101], [200, 201], [300, 301]]
},
"meat": {
"beef": [1000, 1001],
"chicken": [2000, 2001]
}
}
}
&#13;
这将完全返回您想要的输出(在纠正输入不一致之后):
IAppSettings