转换哈希映射数组 [英] converting hash map to array

查看:139
本文介绍了转换哈希映射数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换一个哈希地图

  {
    果:芒果,橙色]
    蔬菜:萝卜]
}

  [
  {类型:果,名:芒果,橙色]},
  {类型:蔬菜,名:萝卜]}
]

该怎么办?


解决方案

您可以像下面这样做(在工作片段):

\r
\r

VAR输入= {\r
    果:芒果,橙色]\r
    蔬菜:萝卜]\r
}\r
\r
VAR输出= [],物品;\r
\r
对于(输入VAR型){\r
    项= {};\r
    项目。形式=类型;\r
    item.name =输入[类型];\r
    output.push(项目);\r
}\r
\r
//显示结果\r
的document.write(JSON.stringify(输出));

\r

\r
\r


或者,如果你或其他人已被延长了对象原型,枚举的属性(我认为这是一个不好的做法个人),那么你可以使用它来保护来自:

\r
\r

VAR输入= {\r
    果:芒果,橙色]\r
    蔬菜:萝卜]\r
}\r
\r
VAR输出= [],物品;\r
\r
对于(输入VAR型){\r
    如果(input.hasOwnProperty(类型)){\r
        项= {};\r
        项目。形式=类型;\r
        item.name =输入[类型];\r
        output.push(项目);\r
    }\r
}\r
\r
//显示结果\r
的document.write(JSON.stringify(输出));

\r

\r
\r


和,使用一些更现代的功能:

\r
\r

VAR输入= {\r
    果:芒果,橙色]\r
    蔬菜:萝卜]\r
};\r
\r
无功输出= Object.keys(输入).MAP(功能(键){\r
   返回{类型:键名:输入[关键]};\r
});\r
\r
//显示结果\r
的document.write(JSON.stringify(输出));

\r

\r
\r

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

解决方案

You can do it like this (in a working snippet):

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));


Or, if you or someone else has been extending the Object prototype with enumerable properties (which I think is a bad practice personally), then you could use this to protect from that:

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));


And, using some more modern functionality:

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));

这篇关于转换哈希映射数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆