Home > OS >  How to transform the nested array of objects in Javascript
How to transform the nested array of objects in Javascript

Time:11-17

I have an array of Object that I want to transform. It contains nested object structure as below :

 [
      {
        geography: 'Austia',
        product: 'RTD Coffee',
        dataType: 'Off-Trade rsp (curr/con, local)',
        timeSeries: [
          {
            year: 2017,
            value: 0.148891823777856,
            highlight: 1,
          },
          {
            year: 2018,
            value: 0.148965642232877,
            highlight: 1,
          },
          {
            year: 2019,
            value: 0.149039460687898,
            highlight: 1,
          },
          {
            year: 2020,
            value: 0.149113279142919,
            highlight: 1,
          },
          {
            year: 2021,
            value: 0.149187097597941,
            highlight: 1,
          },
          {
            year: 2022,
            value: 0.149260916052962,
            highlight: 1,
          },
        ],
      },...
    ];

I want to transform it to the below pattern where the TimeSeries array objects property are extracted and mapped top level as shown below:

[
  {
    geography: 'Austria',
    product: 'RTD Coffee',
    dataType: 'Off-Trade rsp (curr/con, local)',
    2017: 0.148891823777856,
    2018: 0.148965642232877,
    2019: 0.149039460687898,
    2020: 0.149113279142919,
    2021: 0.149187097597941,
    2022: 0.149260916052962,
  },
]

How do I do it?

CodePudding user response:

Try this

function extractYearValue(arr) {
  return arr.map(({timeSeries, ...element}) => {
    const objYearValue = timeSeries.reduce((prev, curr) => {
        return {...prev, [curr.year]: curr.value}
    }, {})
    return {...element, ...objYearValue}
  })
}
  • Related