How to convert JS Object to Array

前端 未结 8 1100
小鲜肉
小鲜肉 2020-12-14 00:24

I need to convert a hash map

{ 
    \"fruit\" : [\"mango\",\"orange\"],
    \"veg\"   : [\"carrot\"]
} 

to

[ 
  { \"type\         


        
8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 01:11

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

提交回复
热议问题