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.

1
  • @Justcode what for? Commented Dec 13, 2018 at 11:34

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

11 Comments

but how to convert data type doing this?
Could you provide an example?
Are you using mongoose? There is no Id type in plain javascript
@Chris K. Sry I am not sure what are you asking, if the id type in input is number it will stay number as you can see here jsfiddle.net/sfu9kt5h/74, but there is no ID type in javascript.
But lets say you just want to convert Id from number to string then you could do this jsfiddle.net/sfu9kt5h/75
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.