Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object containing Objects into array of objects

This is my Object

var data = {     a:{"0": "1"},     b:{"1": "2"},     c:{"2": "3"},     d:{"3": "4"} }; 

This is the output that I expect

data = [      {"0": "1"},     {"1": "2"},     {"2": "3"},     {"3": "4"} ] 
like image 587
Nick Div Avatar asked Nov 07 '14 06:11

Nick Div


People also ask

How do you change an object object to an array of an object?

Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .

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() .

Can we convert object to array in JavaScript?

To convert an object into an array in Javascript, you can use different types of methods. Some of the methods are Object. keys(), Object. values(),and Object.


1 Answers

This works for me

var newArrayDataOfOjbect = Object.values(data)

In additional if you have key - value object try:

const objOfObjs = {    "one": {"id": 3},    "two": {"id": 4}, };  const arrayOfObj = Object.entries(objOfObjs).map((e) => ( { [e[0]]: e[1] } ));  

will return:

[   {     "one": {       "id": 3     }   },   {     "two": {       "id": 4     }   } ] 
like image 111
Thierry Avatar answered Oct 09 '22 08:10

Thierry