How to convert an object to an array in Angular 4?

I want to convert mine Objectto an array, here is my object.

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

I want an array as 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}]
+4
source share
2 answers

Get the keys through Object.keys, and then use the function mapto get the desired result.

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);
Run codeHide result

Another solution can be provided through Object.entriesand restructuring the array.

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

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

console.log(mapped);
Run codeHide result
+10
source

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);
Run codeHide result

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);
Run codeHide result
+5
source

Source: https://habr.com/ru/post/1694847/


All Articles