How to convert JSON object to JavaScript array?

2020-01-23 07:10发布

I need to convert JSON object string to a JavaScript array.

This my JSON object:

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

7条回答
贪生不怕死
2楼-- · 2020-01-23 07:44

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

查看更多
女痞
3楼-- · 2020-01-23 07:45

Suppose you have:

var j = {0: "1", 1: "2", 2: "3", 3: "4"};

You could get the values with:

Object.keys(j).map(function(_) { return j[_]; })

Output:

["1", "2", "3", "4"]
查看更多
何必那么认真
4楼-- · 2020-01-23 07:45

As simple as this !

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
查看更多
叼着烟拽天下
5楼-- · 2020-01-23 07:50
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

查看更多
祖国的老花朵
6楼-- · 2020-01-23 07:55
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);

http://jsfiddle.net/MV5rj/

查看更多
▲ chillily
7楼-- · 2020-01-23 07:56

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:

console.log(Object.entries(json_data));

In both the cases, output will be:

/* output: 
[['2013-01-21', 1], ['2013-01-22', 7]]
*/
查看更多
登录 后发表回答