如何将 JS 对象转换为数组 [英] How to convert JS Object to Array

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

问题描述

我需要转换一个哈希映射

<代码>{"fruit" : ["mango","orange"],蔬菜":[胡萝卜"]}

<预><代码>[{ "type" : "fruit" , "name" : ["mango","orange"] } ,{类型":蔬菜",名称":[胡萝卜"]}]

我该怎么做??

解决方案

你可以这样做(在一个工作片段中):

var input = {"fruit" : ["mango","orange"],蔬菜":[胡萝卜"]}var 输出 = [],项目;for(输入中的var类型){项目 = {};item.type = 类型;item.name = 输入[类型];output.push(item);}//显示结果document.write(JSON.stringify(output));

<小时>

或者,如果您或其他人一直在使用可枚举属性扩展 Object 原型(我个人认为这是一种不好的做法),那么您可以使用它来防止:

var input = {"fruit" : ["mango","orange"],蔬菜":[胡萝卜"]}var 输出 = [],项目;for(输入中的var类型){如果(input.hasOwnProperty(类型)){项目 = {};item.type = 类型;item.name = 输入[类型];output.push(item);}}//显示结果document.write(JSON.stringify(output));

<小时>

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

var input = {"fruit" : ["mango","orange"],蔬菜":[胡萝卜"]};var 输出 = Object.keys(input).map(function(key) {返回 {type: key, name: input[key]};});//显示结果document.write(JSON.stringify(output));

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

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

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