2

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.

2 Answers2

4

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

If you want to convert an object to an array(change type) you can try Object.entries(); In Es2017 There is a property which can be useful in these case, (Object.entries());

const cars = {"BMW": 3, "Tesla": 2, "Audi": 5}
const map = new Map(Object.entries(cars));
console.log(map);

Hope this helps

Akshay Rajput
  • 1,978
  • 1
  • 12
  • 22