gpt4 book ai didi

javascript - 根据属性合并对象数组中的元素

转载 作者:行者123 更新时间:2023-12-04 10:27:39 25 4
gpt4 key购买 nike

我有一个对象数组。每个对象都有一个数量和值(value)属性。如果一个对象具有相同的数量值,我想将该值添加到该对象中。

这是一个示例数组:

const array = [
{
"key": 1,
"amount": 11,
"value": "were"
},
{
"key": 2,
"amount": 6,
"value": "locomotives"
},
{
"key": 3,
"amount": 5,
"value": "They"
},
{
"key": 4,
"amount": 5,
"value": "with"
},
{
"key": 5,
"amount": 4,
"value": "used"
}
]

我想把它改成这样:
const array = [
{
"key": 1,
"amount": 11,
"value": "were"
},
{
"key": 2,
"amount": 6,
"value": "locomotives"
},
{
"key": 3,
"amount": 5,
"value": "They, width"
},
{
"key": 5,
"amount": 4,
"value": "used"
}
]

我试过 reducemap但我似乎无法让它加入,

最佳答案

我认为应该与 .reduce() 一起工作:

const array = [
{
"key": 1,
"amount": 11,
"value": "were"
},
{
"key": 2,
"amount": 6,
"value": "locomotives"
},
{
"key": 3,
"amount": 5,
"value": "They"
},
{
"key": 4,
"amount": 5,
"value": "with"
},
{
"key": 5,
"amount": 4,
"value": "used"
}
];

const result = array.reduce((a, c) => {
const found = a.find(e => e.amount === c.amount);
if (found) found.value = `${found.value}, ${c.value}`;
return found ? a : a.concat(c);
}, []);

console.log(result);


我希望这有帮助!

关于javascript - 根据属性合并对象数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60564341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com