0

Is that possible to sum two different objects from array object and to return single array of object?

let source= [{
  "supplimentKing": [{
    "pwdrName": "zzzzz",
    "pwdrPrice": "2"
  }],
  "protinsAddonOffer": [{
    "pwdrName": "oooo",
    "pwdrPrice": "3"
  }]
}];

result:

[{
  "pwdrName": "zzzzz + oooo",
  "pwdrPrice": "5"
}]

After trying to understand similar SO 1 , SO 2, SO 3 i could not understand how to get expected result.

could some one pls help me how to sum the properties in clean way?

Thanks

10
  • You want to merge all the objects in the array to a single value/object ? Commented Jul 2, 2020 at 11:56
  • 1
    This just needs a for loop and parseInt() - So what have you tried so far to solve this on your own? Commented Jul 2, 2020 at 11:56
  • @Andreas , first i tried to filter price n name then reduce it by summing them both Commented Jul 2, 2020 at 11:59
  • Yes... @Nithish Commented Jul 2, 2020 at 11:59
  • Why .filter()? o.O Just iterate over the elements Commented Jul 2, 2020 at 12:00

1 Answer 1

1

You could use reduce to add values

let source= [{
  "supplimentKing": [{
    "pwdrName": "zzzzz",
    "pwdrPrice": "2"
  }],
  "protinsAddonOffer": [{
    "pwdrName": "oooo",
    "pwdrPrice": "3"
  }],
  "proAddonOffer": [{
    "pwdrName": "iiiii",
    "pwdrPrice": "3"
  }]
}];

p=[]
  source.forEach((o)=>{
    p.push(...Object.values(o))
  })
  v=p.flat()
total= v.reduce((acc,curr)=>{
  acc= [{"pwdrName":curr.pwdrName+"+"+acc.pwdrName,"pwdrPrice":Number(curr.pwdrPrice)+Number(acc.pwdrPrice)}]
  return acc[0]

})
console.log([total])

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

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.