9

I want to convert my Object to array, here is my Object.

{5.0: 10, 28.0: 14, 3.0: 6}

I want array like below

[{"type": 5.0,"value":10},{"type": 28.0,"value":14}, {"type": 3.0,"value":6}]

or

[{"5.0": 10},{"28.0": 14}, {"3.0": 6}]

2 Answers 2

25

Get the keys via Object.keys and then use map function to get the desired output.

const obj = {5.0: 10, 28.0: 14, 3.0: 6};

const mapped = Object.keys(obj).map(key => ({type: key, value: obj[key]}));

console.log(mapped);

Another solution can be provided via Object.entries and array destructuring.

const obj = {5.0: 10, 28.0: 14, 3.0: 6};

const mapped = Object.entries(obj).map(([type, value]) => ({type, value}));

console.log(mapped);

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

4 Comments

in your second approach when returning value is 'auto creating key -value ' is about destructuring too?
Destructuring part is going only in the parameters - ([type, value]). I get an array in the parameters and destruct them into single parameters instead of doing param[0] and param[1]
and how about this part ({type, value})? you are supplying only values and returned array has keys too
Yes, when you just pass the property, it creates a key with the same name. In this case I have an object with two properties - type and value. This {type, value} is equivalent to {type: type, value: value}
11

Use Object.keys and array.map:

var obj = {5.0: 10, 28.0: 14, 3.0: 6}

var arr = Object.keys(obj).map(key => ({type: key, value: obj[key]}));

console.log(arr);

And if your browser supports Object.entries, you can use it:

var obj = {5.0: 10, 28.0: 14, 3.0: 6}

var arr = Object.entries(obj).map(([type, value]) => ({type, value}));

console.log(arr);

2 Comments

Same answer no duplicate answer please
@AvanishKumar don't have intention to duplicate someone's answer, I answered at the time he answered

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.