Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Object to array in Angular 4?

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}]
like image 872
Amarish Rathod Avatar asked Mar 14 '18 06:03

Amarish Rathod


People also ask

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .


2 Answers

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);
like image 54
Suren Srapyan Avatar answered Oct 31 '22 04:10

Suren Srapyan


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);
like image 25
Faly Avatar answered Oct 31 '22 04:10

Faly