Search code examples
javascriptangulartypescriptlodash

How to convert nested array to normal array and change types?


I have the following structure of array:

[{Id: Number, Attributes: {Name: String, Age: String, Height: String}}]

And I want to convert it into the:

[{Id: Number, Name: String, Age: Number, Height: Number}]

Also how to convert "2018-12-12 09:19:40" to an Date object? While converting the entire array.

How to do this? Using lodash or not.


Solution

  • You could use map with spread syntax ....

    const data = [{Id: 'Number', Attributes: {Name: 'String', Age: 'String', Height: 'String'}}]
    const res = data.map(({Attributes, ...rest}) => ({...rest, ...Attributes}))
    console.log(res)

    To convert the data types you could use some nested destructuring.

    const data = [{Id: 'Number', Attributes: {Name: 'String', Age: '20', Height: '123'}}]
    const res = data.map(({Attributes: {Age, Height, ...attr}, ...rest}) => ({
      ...rest,
      ...attr,
      Age: +Age,
      Height: +Height
    }))
    console.log(res)