Sam*_*Sam 37 javascript arrays hash
我需要转换哈希映射
{
"fruit" : ["mango","orange"],
"veg" : ["carrot"]
}
Run Code Online (Sandbox Code Playgroud)
至
[
{ "type" : "fruit" , "name" : ["mango","orange"] } ,
{ "type" : "veg" , "name" : ["carrot"] }
]
Run Code Online (Sandbox Code Playgroud)
我怎么做??
jfr*_*d00 38
你可以这样做(在一个工作片段中):
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));Run Code Online (Sandbox Code Playgroud)
或者,如果您或其他人一直在扩展Object具有可枚举属性的原型(我认为这是个坏习惯),那么您可以使用它来保护:
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));Run Code Online (Sandbox Code Playgroud)
并且,使用一些更现代的功能:
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));Run Code Online (Sandbox Code Playgroud)
ZER*_*ER0 25
在支持ES5的浏览器中 - 或者为其添加垫片的位置:
var stuff = {
"fruit" : ["mango","orange"],
"veg" : ["carrot"]
}
var array = Object.keys(stuff).map(function(key) {
return {"type" : key, "name" : stuff[key] }
})
Run Code Online (Sandbox Code Playgroud)
请参阅:Object.keys,Array的映射
或者,以旧时尚的方式:
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] })
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在这两种情况下,数组的值都是共享的,因为在JS中,对象是通过引用传递的.因此,例如,stuff["fruit"]并array[0].name指向数组的相同引用["mango", "orange"].这意味着,如果您更改其中一个,另一个也将更改:
stuff["fruit"].push("apple");
alert(array[0].name); // "mango", "orange", "apple"
Run Code Online (Sandbox Code Playgroud)
为避免这种情况,您可以使用slice来获得数组的一级深层副本.所以在上面的代码中,而不是:
"name" : stuff[key]
Run Code Online (Sandbox Code Playgroud)
你将会有:
"name" : stuff[key].slice(0)
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.
对于那些使用ES6地图的人......
假设你有......
const m = new Map()
m.set("fruit",["mango","orange"]);
m.set("veg",["carrot"]);
Run Code Online (Sandbox Code Playgroud)
您可以使用...
const arr = Array.from(map, ([key, val]) => {
return {type: key, name: val};
});
Run Code Online (Sandbox Code Playgroud)
请注意,Array.from采用iterables和类似数组的对象.
小智 6
我想提供一个"oneline"解决方案:
var b = Object.keys(a).map(e => { return { type:e, name:a[e] } });
Run Code Online (Sandbox Code Playgroud)
经济实惠的服务.问题要求将对象转换为数组,所以我不会重复上面的答案,不是吗?