[英]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. 因此,我需要将一个
{"0":"sometext","1":"someothertext"}
这样的json对象转换为一个javascript数组,其索引与整数匹配,并且数据与字符串匹配。 I tried using JSON.parse() but it didn't work since this happens. 我尝试使用JSON.parse(),但是由于这种情况,它没有用。
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.