我需要转换一个哈希图

{
    "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);
}

// display result
document.write(JSON.stringify(output));



或者,如果您或其他人已经使用可枚举的属性扩展了Object原型(prototype)(我个人认为这是不好的做法),那么您可以使用它来防止这种情况:

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));



并且,使用一些更现代的功能:

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));

关于javascript - 如何将JS对象转换为数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10336794/

10-12 13:03
查看更多