简体   繁体   中英

How can I turn a json object into a javascript array

So, I need to convert a json object like this {"0":"sometext","1":"someothertext"} into a javascript array with the index matching the integer and the data at the index the string. I tried using JSON.parse() but it didn't work since this happens.

var json = '{"0":"sometext","1":"someothertext"}';
var obj = JSON.parse(json);
//Then when I would want to assign a part of the object to a variable this gives me an error
var somevar = obj.0;

You can simply iterate over every property in the object and assign them as values in the array:

var obj = {"0":"sometext","1":"someothertext"};
var arr = [];

Object.keys(obj).forEach(function (key) {
    arr[key] = obj[key]
});

Use bracket notation:

Change

var somevar = obj.0;

to

var somevar = obj[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM