Javascript 如何将 JS 对象转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10336794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:55:16  来源:igfitidea点击:

How to convert JS Object to Array

javascriptarrayshash

提问by Sam

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

我怎么做??

采纳答案by jfriend00

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 Objectprototype with enumerable properties (which I think is a bad practice personally), then you could use this to protect from that:

或者,如果您或其他人一直在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));



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

回答by ZER0

In a browser that supports ES5 – or where you added a shimfor it:

在支持 ES5 的浏览器中——或者你为它添加了shim的地方:

var stuff = { 
    "fruit" : ["mango","orange"],
    "veg"   : ["carrot"]
}

var array = Object.keys(stuff).map(function(key) {
    return {"type" : key, "name" : stuff[key] }
})

See: Object.keys, Array's map

请参阅:Object.keys数组的映射

Or, in the old fashion way:

或者,以旧时尚的方式:

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] })
    }
}

Please notice that in both cases the array's value are shared because in JS the objects are passed by reference. So, for instance, stuff["fruit"]and array[0].namepoints to the same reference of the array ["mango", "orange"]. It means, if you change one of them, the other will be changed as well:

请注意,在这两种情况下,数组的值都是共享的,因为在 JS 中,对象是通过引用传递的。因此,例如,stuff["fruit"]andarray[0].name指向数组的相同引用["mango", "orange"]。这意味着,如果您更改其中一个,另一个也将更改:

stuff["fruit"].push("apple");
alert(array[0].name); // "mango", "orange", "apple"

To avoid that, you can use sliceto have a one-level deep copy of your array. So in the code above, instead of:

为避免这种情况,您可以使用slice来获得数组的一层深层副本。所以在上面的代码中,而不是:

"name" : stuff[key]

you will have:

你将会有:

"name" : stuff[key].slice(0)

Hope it helps.

希望能帮助到你。

回答by WoodenKitty

For those using ES6 maps...

对于那些使用 ES6 地图的人...

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.fromtakes iterables as well as array-like objects.

请注意,Array.from接受可迭代对象以及类似数组的对象。

回答by Roberto

I would like to give an "oneline" solution:

我想给出一个“oneline”解决方案:

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?

为您服务的文字经济。要求将对象转换为数组的问题,所以我没有重复上面的答案,不是吗?

回答by allenhwkim

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]

回答by Anurag Uniyal

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"]}]

回答by toshi

In case of using underscore.js:

如果使用 underscore.js:

var original = { 
   "fruit" : ["mango","orange"],
   "veg"   : ["carrot"]
}
var converted = _.map(original, function(name, type){
   return {
      type: type, 
      name: name
   };
});

回答by Dev

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()   
]