How to convert object containing Objects into array of objects

南楼画角 提交于 2019-11-26 11:01:14

问题


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\"}
]

回答1:


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},
]



回答2:


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

var myData = Object.keys(data).map(key => {
    return data[key];
})

This works for me




回答3:


You would have to give a name to each value in the object.

Once you fix the first object, then you can do it using push.

var data = {
    1: {"0": "1"},
    2: {"1": "2"},
    3 : {"2": "3"},
    4: {"3": "4"}
};

var ar = [];
for(item in data){
    ar.push(data[item]);
 }

console.log(ar);

http://jsfiddle.net/nhmaggiej/uobrfke6/




回答4:


var array = [];
for(var item in data){
    // this condition is required to prevent moving forward to prototype chain
    if(data.hasOwnProperty(item)){
        array.push(data[item]);
    } 
}



回答5:


I get what you want ! Here is your solution,

var dataObject=[{name:'SrNo',type:'number'}];

And to access or store the array use

dataObject[0].srno=1;
dataObject[0].srno=2;

Hope this is what you needed.




回答6:


This worked for me. And it seems to be well supported.

toArray(obj_obj) {
    return Object.keys(obj_obj).map(i => obj_obj[i]);
}

https://medium.com/chrisburgin/javascript-converting-an-object-to-an-array-94b030a1604c




回答7:


The accepted answer doesn't take into account the OP wanted to get rid of the keys. This returns only the objects, not their parent key.

Object.entries(ObjOfObjs).map(e => e[1]) outputs:

[ 
  {"0": "1"},
  {"1": "2"},
  {"2": "3"},
  {"3": "4"}
]


来源:https://stackoverflow.com/questions/26795643/how-to-convert-object-containing-objects-into-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!