I need to convert a hash map
{
\"fruit\" : [\"mango\",\"orange\"],
\"veg\" : [\"carrot\"]
}
to
[
{ \"type\
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
};
});
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]
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?
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.
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"]}]
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()
]