Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按数组中的相同值合并对象_Javascript_Arrays - Fatal编程技术网

Javascript 按数组中的相同值合并对象

Javascript 按数组中的相同值合并对象,javascript,arrays,Javascript,Arrays,我需要组合价格相同的对象并添加数量(amount) 例如: [ {price: 25.1, amount: 32}, {price: 45.2, amount: 45}, {price: 25.1, amount: 25}, {price: 44.0, amount: 13}, {price: 45.2, amount: 23} ] 结果: [ {price: 25.1, amount: 57}, // 32 + 25 {price: 4

我需要组合价格相同的对象并添加数量(
amount

例如:

[
    {price: 25.1, amount: 32},
    {price: 45.2, amount: 45},
    {price: 25.1, amount: 25},
    {price: 44.0, amount: 13},
    {price: 45.2, amount: 23}
]
结果:

[
    {price: 25.1, amount: 57}, // 32 + 25
    {price: 45.2, amount: 68}, // 45 + 23
    {price: 44.0, amount: 13},
]
您可以对对象使用
Array#reduce
来存储每个价格的金额

const示例=[
{价格:25.1,金额:32},
{价格:45.2,金额:45},
{价格:25.1,金额:25},
{价格:44.0,金额:13},
{价格:45.2,金额:23}
]
const res=Object.values(例如.reduce((acc,{price,amount})=>
((acc[price]=acc[price]|{price,amount:0})。amount+=amount,acc),{});
控制台日志(res)