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

Mr. Learner
  • 978
  • 2
  • 18
  • 48
  • You want to merge all the objects in the array to a single value/object ? – Nithish Jul 02 '20 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? – Andreas Jul 02 '20 at 11:56
  • @Andreas , first i tried to filter price n name then reduce it by summing them both – Mr. Learner Jul 02 '20 at 11:59
  • Yes... @Nithish – Mr. Learner Jul 02 '20 at 11:59
  • Why `.filter()`? o.O Just iterate over the elements – Andreas Jul 02 '20 at 12:00
  • because there lot of properties inside the response but i want to do summation on selected offer combination – Mr. Learner Jul 02 '20 at 12:02
  • @Andreas i dont want to complicate by using nested or two independent for loops since it has two different object from same array. – Mr. Learner Jul 02 '20 at 12:09
  • why does expected output have key supplimentking if it pulls data from other places too. do any/all of those arrays of objects contain additional elements. – James Jul 02 '20 at 12:17
  • @James ""supplimentking is just for understanding. and Yest has many. i just give necessary properties for summation i edited my thread. Thanks – Mr. Learner Jul 02 '20 at 12:19
  • why is each object in the source array, an array of object (one...)? And prices as Numbers - this makes more sense: `source= [ { "pwdrName": "zzzzz", "pwdrPrice": 2 }, { "pwdrName": "oooo", "pwdrPrice": 3 } ];` – iAmOren Jul 02 '20 at 13:03

1 Answers1

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])
Sven.hig
  • 4,449
  • 2
  • 8
  • 18