I have an array of objects like the following:
[
{
'Product': 'P1',
'Price': 150,
'Location': 1,
},
{
'Product': 'P1',
'Price': 100,
'Location': 1,
},
{
'Product': 'P1',
'Price': 200,
'Location': 2,
},
{
'Product': 'P2',
'Price': 10,
'Location': 1,
},
{
'Product': 'P2',
'Price': 130,
'Location': 1,
},
{
'Product': 'P3',
'Price': 40,
'Location': 1,
}
]
I need to add up all the prices for objects with the same product and same location. For the example above the result would be:
[
{
'Product': 'P1',
'Price': 250, // price is the sum of both similar in location and product
'Location': 1,
},
{
'Product': 'P1',
'Price': 200,
'Location': 2, // same product but different location
},
{
'Product': 'P2',
'Price': 140, //sum of same
'Location': 1,
},
{
'Product': 'P3',
'Price': 40,
'Location': 1,
},
]
I have searched several similar issues, but those were dealing with only one key to check for, I have different keys (product and location - may be more than 2 in the future) to identify as different.
const input = [
{
'Product': 'P1',
'Price': 150,
'Location': 1,
},
{
'Product': 'P1',
'Price': 100,
'Location': 1,
},
{
'Product': 'P1',
'Price': 200,
'Location': 2,
},
{
'Product': 'P2',
'Price': 10,
'Location': 1,
},
{
'Product': 'P2',
'Price': 130,
'Location': 1,
},
{
'Product': 'P3',
'Price': 40,
'Location': 1,
}
]
const output = []
input.forEach(item => {
const index = output.findIndex(o => o.Product === item.Product && o.Location === item.Location);
if (index === -1) {
output.push(item);
} else {
output[index].Price += item.Price;
}
});
console.log(output);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다