How to convert JS Object to Array

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

I need to convert a hash map

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

to

[ 
  { \"type\         


        
相关标签:
8条回答
  • 2020-12-14 00:46

    In case of using underscore.js:

    var original = { 
       "fruit" : ["mango","orange"],
       "veg"   : ["carrot"]
    }
    var converted = _.map(original, function(name, type){
       return {
          type: type, 
          name: name
       };
    });
    
    0 讨论(0)
  • 2020-12-14 00:54

    Not exactly the answer you are looking for, but it could be useful for general purpose.

    var hash2Array = function(hash, valueOnly) {
      return Object.keys(hash).map(function(k) {
        if (valueOnly) {
          return hash[k];
        } else {
          var obj={};
          obj[k] = hash[k];
          return obj;
        }
      });
    };
    
    //output
    hash2Array({a:1, b:2});     // [{a:1}, {b:2}]
    hash2Array({a:1, b:2},true) // [1,2]
    
    0 讨论(0)
  • 2020-12-14 01:02

    I would like to give an "oneline" solution:

    var b = Object.keys(a).map(e => { return { type:e, name:a[e] } });
    

    Economy of words at your service. Question asked for translating an object to an array, so I'm not duplicating above answer, isn't it?

    0 讨论(0)
  • 2020-12-14 01:03

    For those using ES6 maps...

    Assuming you have...

    const m = new Map()
    m.set("fruit",["mango","orange"]);
    m.set("veg",["carrot"]);
    

    You can use...

    const arr = Array.from(map, ([key, val]) => {
      return {type: key, name: val};
    });
    

    Note that Array.from takes iterables as well as array-like objects.

    0 讨论(0)
  • 2020-12-14 01:05

    It looks simple, key of your map is type and values are name, so just loop thru map and insert object in a list e.g.

    var d = { "fruit" : ["mango","orange"],"veg" :["carrot"]} 
    var l = []
    for(var type in d){
        l.push({'type':type, 'name': d[type]})
    }
    console.log(l)
    

    output:

    [{"type":"fruit","name":["mango","orange"]},{"type":"veg","name":["carrot"]}]
    
    0 讨论(0)
  • 2020-12-14 01:07

    No Need of loop

    var a = { 
       "fruit" : ["mango","orange"],    
       "veg"   : ["carrot"]
    
    
    };  
    
    var b = [  
        { "type" : "fruit" , "pop" : function(){this.name = a[this.type]; delete this.pop; return this} }.pop() ,          
        { "type" : "veg" ,   "pop" : function(){this.name = a[this.type]; delete this.pop; return this} }.pop()   
    ]
    
    0 讨论(0)
提交回复
热议问题