Javascript 如何将包含对象的对象转换为对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26795643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert object containing Objects into array of objects
提问by Nick Div
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"}
]
回答by Thierry
This works for me
这对我有用
var newArrayDataOfOjbect = Object.values(data)
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},
]
回答by Shuwei
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
这对我有用
回答by mags
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.
一旦你修复了第一个对象,你就可以使用 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);
回答by frogatto
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]);
}
}
回答by Ashitosh birajdar
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.
希望这是你所需要的。
回答by Omar
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
https://medium.com/chrisburgin/javascript-converting-an-object-to-an-array-94b030a1604c
回答by Matt Weber
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.
接受的答案没有考虑到 OP 想要摆脱密钥。这仅返回对象,而不返回它们的父键。
Object.entries(ObjOfObjs).map(e => e[1])outputs:
Object.entries(ObjOfObjs).map(e => e[1])输出:
[
{"0": "1"},
{"1": "2"},
{"2": "3"},
{"3": "4"}
]

