How to convert JS Object to Array

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

I need to convert a hash map

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

to

[ 
  { \"type\         


        
8条回答
  •  一向
    一向 (楼主)
    2020-12-14 01:08

    In a browser that supports ES5 – or where you added a shim for it:

    var stuff = { 
        "fruit" : ["mango","orange"],
        "veg"   : ["carrot"]
    }
    
    var array = Object.keys(stuff).map(function(key) {
        return {"type" : key, "name" : stuff[key] }
    })
    

    See: Object.keys, Array's map

    Or, in the old fashion way:

    var stuff = { 
        "fruit" : ["mango","orange"],
        "veg"   : ["carrot"]
    }
    
    var array = []
    
    for (var key in stuff) {
        if (stuff.hasOwnProperty(key)) {
            array.push({"type" : key, "name" : stuff[key] })
        }
    }
    

    Please notice that in both cases the array's value are shared because in JS the objects are passed by reference. So, for instance, stuff["fruit"] and array[0].name points to the same reference of the array ["mango", "orange"]. It means, if you change one of them, the other will be changed as well:

    stuff["fruit"].push("apple");
    alert(array[0].name); // "mango", "orange", "apple"
    

    To avoid that, you can use slice to have a one-level deep copy of your array. So in the code above, instead of:

    "name" : stuff[key]
    

    you will have:

    "name" : stuff[key].slice(0)
    

    Hope it helps.

提交回复
热议问题