如何从动态数组中搜索相同的值并使用JS求和

时间:2019-07-17 12:51:54

标签: javascript jquery arrays javascript-objects

我有一个动态对象,如:

 [ 
  { age: 35 },
  { weight: 60 },
  { age: 50 },
  { weight: 54 },
  { height: 175 },
  { age: 3.5 }
]

我想找到和总和一样的值:-

 [ 
  { age:88.5 },
  { height: 175 },
  { weight: 114 }
 ]

2 个答案:

答案 0 :(得分:2)

尝试一下

const data  =   [ 
  { age: 35 },
  { weight: 60 },
  { age: 50 },
  { weight: 54 },
  { height: 175 },
  { age: 3.5 }
];

const result  = Object.entries(data.reduce((acc, ele)=> {
const key  = Object.keys(ele)[0];
acc[key]  = (acc[key]||0)+  ele[key]; return acc},[]))
.map(([k, v])=>({[k]:v}))

console.log(result);

答案 1 :(得分:1)

使用forEach()对数组进行迭代,对对象元素进行另一迭代并计算总和。

let sum = {};
const data = [
    { age: 35 },
    { weight: 60 },
    { age: 50 },
    { weight: 54 },
    { height: 175 },
    { age: 3.5 }
]

data.forEach((item) => {
    for (let key in item) sum[key] = sum[key] ? sum[key] + item[key] : item[key]
})

console.log([sum])

我们还可以使用reduce()函数来计算总和。

    const data = [
        { age: 35 },
        { weight: 60 },
        { age: 50 },
        { weight: 54 },
        { height: 175 },
        { age: 3.5 }
    ]

let sum = data.reduce((all, curr) => {
    let key = Object.keys(curr)[0];
    all[key] = all[key] ? all[key] + curr[key] : curr[key]
    return all
}, {})

console.log([sum])