How to convert JS Object to Array

2019-01-23 11:04发布

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??

8条回答
太酷不给撩
2楼-- · 2019-01-23 11:20

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
   };
});
查看更多
男人必须洒脱
3楼-- · 2019-01-23 11:23

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]
查看更多
唯我独甜
4楼-- · 2019-01-23 11:25

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"]}]
查看更多
家丑人穷心不美
5楼-- · 2019-01-23 11:27

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.

查看更多
Fickle 薄情
6楼-- · 2019-01-23 11:27

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?

查看更多
虎瘦雄心在
7楼-- · 2019-01-23 11:34

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()   
]
查看更多
登录 后发表回答