-5

I have a dynamic object like :

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

I want to find and the sum same value like that:-

 [ 
  { age:88.5 },
  { height: 175 },
  { weight: 114 }
 ]
5
  • 2
    Haven't you tried anything? Commented Jul 17, 2019 at 12:54
  • No validated answer here, but it could help you : stackoverflow.com/questions/40262445/… Commented Jul 17, 2019 at 12:55
  • Possible duplicate of Merge objects with same key in javascript Commented Jul 17, 2019 at 12:55
  • Try doing something, search "walking json" or "traverse" medium.com/front-end-weekly/… Commented Jul 17, 2019 at 12:56
  • Why does the result is an array of object with a single property which, if the code works properly, should be unique keys? You should store it in a single object: way easier to manipulate. Commented Jul 17, 2019 at 12:57

2 Answers 2

1

Use forEach() to make an iteration on array and another iteration on object element and calculate the sum.

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])

Also we can use reduce() function to calculate the sum.

    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])

Sign up to request clarification or add additional context in comments.

3 Comments

This is the perfect case for .reduce() ;)
@Karl-AndréGagnon yes, I didn't think it. :)
@Karl-AndréGagnon I tried it with reduce but I was unable to get any answer.
1

Try this

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.