Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create multiple objects from array's value in javascript?

I have an array like this :

const data = [{
color:"red",
to:1,
from:2,
opacity:12

}]

I want something like this :

const converted = [{from:2},{to:1},{opacity:12}]

what i am trying is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const mappeData = data.map(({from,to,opacity})=>({from:from},{to:to},{opacity:opacity}))

but this is not working

>Solution :

So you can loop through the array and for each object we can get the keys of the objects in the array and use a map to transform them to our desired output, Then the output will return an array, but we can use flatMap which will flatten the arrays returned into a single array of objects!

Thanks pilchard for teaching about flatMap!

const data = [{
color:"red",
to:1,
from:2,
opacity:12

}]

const arr = data.flatMap(x => Object.keys(x).map(data => ({[data]: x[data]})))

console.log(arr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading