Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

React looping and creating new array with nested objects in javascript ?

By M.K. Verma · 3 May 2022

React looping and creating new array with nested objects in javascript ?

You can use reduce to group positions by userid.

const positions =  [{
      "name": "AAPL",
      "ownerTotals": {uid: "xxx", totaledAmount: 140 }, {uid: "yyy", totaledAmount: 10}
    },
    {
      "name": "TSLA",
      "ownerTotals": {uid: "xxx", totaledAmount: 11 }, {uid: "yyy", totaledAmount: 2}
    }]

const posByUid = positions.reduce((acc, current) => {
 const name = current.name
 current.positions.forEach(position => {
   if (!acc[position.uid]) {
    acc[position.uid] = []
   }

   acc[position.uid] = {name, totaledAmount: position.totaledAmount}
 })
 return acc
}, {})