How to convert JSON object to JavaScript array?

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?

Answers:

Answer
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/

Answer

If you have a well-formed JSON string, you should be able to do

var as = JSON.parse(jstring);

I do this all the time when transfering arrays through AJAX.

Answer

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

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]]
*/
Answer

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

Answer

As simple as this !

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
Answer
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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.