将对象键值对转换为 Javascript 中的一系列数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31784344/
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
Convert object key-value pairs to a series of arrays in Javascript
提问by Akshat Mahajan
I am new to Javascript. I have a Javascript object like so:
我是 Javascript 的新手。我有一个像这样的 Javascript 对象:
s = {"Toothless":"Dragon","Foo":"Bar"};
I need to convert it into a series of arrays, like so:
我需要将其转换为一系列数组,如下所示:
out = [["Toothless","Dragon"],["Foo","Bar"]];
This is the reverse of what is discussed in Convert JavaScript array of 2 element arrays into object key value pairs. A JQuery solution is acceptable.
这与将 2 个元素数组的 JavaScript 数组转换为对象键值对中讨论的相反。JQuery 解决方案是可以接受的。
回答by baao
You can map over the items to achieve this:
您可以映射项目以实现此目的:
s = {"Toothless":"Dragon","Foo":"Bar"};
var out = Object.keys(s).map(function(data){
return [data,s[data]];
});
console.log(out);
回答by Kobi
let s = {"Toothless":"Dragon","Foo":"Bar"};
let out = Object.entries(s);
and you get out
as an array of small arrays,
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
你会得到out
一个小数组的数组,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
回答by user5185140
var s = {"Toothless":"Dragon","Foo":"Bar"};
var out = [];
for (var key in s){
out.push([key, s[key]]);
}
回答by Gagan
Try this using jQuery.
使用 jQuery 试试这个。
var tempArr = [];
s = {"Toothless":"Dragon","Foo":"Bar"};
$.each(s,function(i,v){
tempArr.push([i,v]);
});