Jacob Nelson
Jacob Nelson

Reputation: 473

Map a javascript object into array structure

I have an object like this:

{"label":["Option 1","Option 2","Option 3"],"share":[0.0650068849312104,0.00873977167120444,0.00873977167120444]}

I need to convert this to an array that looks like this:

[{label: "Option 1", share: 0.0650068849312104}, {label: "Option 2", share: 0.00873977167120444}, {label: "Option 3", share: 0.00873977167120444}]

In other words, it needs to be an array of objects of the same length as the number of data points.

I am very new to javascript, so I apologize if this is a bad question. I haven't been able to find a satisfactory reason elsewhere. Do I need to use something like object.keys()? If so, how do I use it? It's just not clear to me how to convert this into an array and map it into this structure.

Any and all help is appreciated!

Edit: removing reference to JSON

Upvotes: 2

Views: 147

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138277

 const result = obj.label.map( (label,index) => ({label, share:obj.share[index]}) );

Where obj is the first code row of your question ( or a reference pointing to it), then result will be the second code row.

Upvotes: 4

Related Questions