我的 collection 有不同的数组 我怎样才能合并这个数组 javascript?
My collection have difference array how can I merge this array javascript?
我的数组有问题。我想将不同的数组合并在一起。不同的数组可以不止于此。我将在下面展示我的 collection。
let myCollection = [
{
_id: '0003',
avgCost: 10,
itemId: '0003',
onHand: 12,
inventoriesValue: 120,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 12,
inventoriesValue: 240,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 10,
inventoriesValue: 200,
}
]
我想通过 itemId 组合元素来实现下面的结果。
[
{
_id: '0003',
avgCost: 10,
itemId: '0003',
onHand: 12,
inventoriesValue: 120,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 22,
inventoriesValue: 440,
},
]
如果我理解这个问题,那么您正在尝试对两个数组执行并集,但要进行对象比较。有几种方法可以做到这一点。
如果您使用的是 lodash
,您可以对两个数组执行类似的操作:
_.unionWith(arr1, arr2, _.isEqual);
或者,如果您有一个数组数组,您可以这样做:
_.uniqWith(_.flatten(arrays), _.isEqual);
基本上您需要创建一个新数组来汇总原始数组中的所有相同元素。下面的代码应该适用于小型数组。
const targetArray = []; // an empty array for the results
myCollection.forEach(mc => { // loop over the original array
let i = targetArray.findIndex(ta => ta.itemId == mc.itemId); // match on itemId
if (i > -1) { // found a match
targetArray[i].onHand += mc.onHand; // increment the onHand value
targetArray[i].inventoriesValue += mc.inventoriesValue; // and inventoriesValue
} else { // no match found
targetArray.push(mc); // push the element
}
});
注意这里假设每个元素中的avgCost
是相同的。如果它们不同,则您需要根据要添加的新库存取加权平均值。
我的数组有问题。我想将不同的数组合并在一起。不同的数组可以不止于此。我将在下面展示我的 collection。
let myCollection = [
{
_id: '0003',
avgCost: 10,
itemId: '0003',
onHand: 12,
inventoriesValue: 120,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 12,
inventoriesValue: 240,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 10,
inventoriesValue: 200,
}
]
我想通过 itemId 组合元素来实现下面的结果。
[
{
_id: '0003',
avgCost: 10,
itemId: '0003',
onHand: 12,
inventoriesValue: 120,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 22,
inventoriesValue: 440,
},
]
如果我理解这个问题,那么您正在尝试对两个数组执行并集,但要进行对象比较。有几种方法可以做到这一点。
如果您使用的是 lodash
,您可以对两个数组执行类似的操作:
_.unionWith(arr1, arr2, _.isEqual);
或者,如果您有一个数组数组,您可以这样做:
_.uniqWith(_.flatten(arrays), _.isEqual);
基本上您需要创建一个新数组来汇总原始数组中的所有相同元素。下面的代码应该适用于小型数组。
const targetArray = []; // an empty array for the results
myCollection.forEach(mc => { // loop over the original array
let i = targetArray.findIndex(ta => ta.itemId == mc.itemId); // match on itemId
if (i > -1) { // found a match
targetArray[i].onHand += mc.onHand; // increment the onHand value
targetArray[i].inventoriesValue += mc.inventoriesValue; // and inventoriesValue
} else { // no match found
targetArray.push(mc); // push the element
}
});
注意这里假设每个元素中的avgCost
是相同的。如果它们不同,则您需要根据要添加的新库存取加权平均值。