如何将 JSON 对象转换为 JavaScript 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14528385/
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
How to convert JSON object to JavaScript array?
提问by user1960311
I need to convert JSON object string to a JavaScript array.
我需要将 JSON 对象字符串转换为 JavaScript 数组。
This my JSON object:
这是我的 JSON 对象:
{"2013-01-21":1,"2013-01-22":7}
And I want to have:
我想要:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['2013-01-21', 1],
['2013-01-22', 7]
]);
How can I achieve this?
我怎样才能做到这一点?
采纳答案by salexch
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];
for(var i in json_data)
result.push([i, json_data [i]]);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);
回答by aggaton
If you have a well-formed JSON string, you should be able to do
如果你有一个格式良好的 JSON 字符串,你应该能够做到
var as = JSON.parse(jstring);
I do this all the time when transfering arrays through AJAX.
我在通过 AJAX 传输数组时一直这样做。
回答by Roger Garzon Nieto
function json2array(json){
var result = [];
var keys = Object.keys(json);
keys.forEach(function(key){
result.push(json[key]);
});
return result;
}
See this complete explanation: http://book.mixu.net/node/ch5.html
看到这个完整的解释:http: //book.mixu.net/node/ch5.html
回答by mvallebr
Suppose you have:
假设你有:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with:
您可以通过以下方式获取值:
Object.values(j)
Output:
输出:
["1", "2", "3", "4"]
回答by Rakesh Sharma
This will solve the problem:
这将解决问题:
const json_data = {"2013-01-21":1,"2013-01-22":7};
const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);
console.log(arr);
Or using Object.entries()method:
或者使用Object.entries()方法:
console.log(Object.entries(json_data));
In both the cases, output will be:
在这两种情况下,输出将是:
/* output:
[['2013-01-21', 1], ['2013-01-22', 7]]
*/
回答by NuOne
You can insert object items to an array as this
您可以像这样将对象项插入到数组中
let obj = {
'1st': {
name: 'stackoverflow'
},
'2nd': {
name: 'stackexchange'
}
};
let wholeArray = Object.keys(obj).map(key => obj[key]);
console.log(wholeArray);
回答by CCC
As simple as this !
就这么简单!
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);

