如何将JS对象转换为数组 [英] How to convert JS Object to Array
本文介绍了如何将JS对象转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要转换一个散列图
{
fruit:[mango,orange ],
veg:[carrot]
}
到
[
{type:fruit,name:[mango,orange ]},
{type:veg,name:[carrot]}
]
我该怎么做?
解决方案
你可以这样做(在工作片段中):
var input = {fruit:[mango,orange],veg:[ carrot]} var output = [],item; for(var type in input){item = {}; item.type = type; item.name = input [type]; output.push(item);} //显示resultdocument.write(JSON.stringify(输出));
或者,如果您或其他人一直在使用可枚举属性扩展 Object
(我个人认为这是个不好的做法),那么你可以用它来保护它:
var input = {fruit [mango,orange],veg:[carrot]} var output = [],item; for(var type in input){if(input.hasOwnProperty(type)){item = {} ; item.type = type; item.name = input [type]; output.push(项目); $} $ // $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b
而且,使用更现代的功能: jsdata-hide =false>
var input = {fruit :[mango,orange],veg:[carrot]}; var output = Object.keys(input).map(function(key){return {type:key,name:input [ key)};}); //显示resultdocument.write(JSON.stringify(output));
I need to convert a hash map
{
"fruit" : ["mango","orange"],
"veg" : ["carrot"]
}
to
[
{ "type" : "fruit" , "name" : ["mango","orange"] } ,
{ "type" : "veg" , "name" : ["carrot"] }
]
how do I do that??
解决方案
You can do it like this (in a working snippet):
var input = {
"fruit" : ["mango","orange"],
"veg" : ["carrot"]
}
var output = [], item;
for (var type in input) {
item = {};
item.type = type;
item.name = input[type];
output.push(item);
}
// display result
document.write(JSON.stringify(output));
Or, if you or someone else has been extending the Object
prototype with enumerable properties (which I think is a bad practice personally), then you could use this to protect from that:
var input = {
"fruit" : ["mango","orange"],
"veg" : ["carrot"]
}
var output = [], item;
for (var type in input) {
if (input.hasOwnProperty(type)) {
item = {};
item.type = type;
item.name = input[type];
output.push(item);
}
}
// display result
document.write(JSON.stringify(output));
And, using some more modern functionality:
var input = {
"fruit" : ["mango","orange"],
"veg" : ["carrot"]
};
var output = Object.keys(input).map(function(key) {
return {type: key, name: input[key]};
});
// display the result
document.write(JSON.stringify(output));
这篇关于如何将JS对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文