简体   繁体   中英

Converting a JSON object into JS array

This is what I get as a jQuery response from Wordpress database after json_encode :

[{ "id" : "33", "first_name" : "Oleg", "last_name" : "Smith" }]

Because it is multi-dimensional in nature, but there is just one row, hence you have square brackets on both ends.

Therefore ALL methods I found on SO when trying to parse and then convert to a JS array fail, eg

for(var x in parsed){
    arr.push(parsed[x]);
}

OR

var arr = $.map(obj, function(el) { return el; });

OR

var arr = Object.keys(obj).map(function(k) { return obj[k] });

OR

for(var i in JsonObj) {
    if(JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
        array[+i] = JsonObj[i];
    }
}

I can manually remove square brackets and proceed OR I can push manually each item:

aaData.push(searchObj[0].first_name);

But I don't like either of the solutions I have. Do I have other options?

PS. I need a JS array so that I can loop through with [i] .

You can do the following to push all values to aaData array:

var parsed = [{ "id" : "33", "first_name" : "Oleg", "last_name" : "Smith" }];
var aaData = [];
for(key in parsed[0]) { aaData.push(parsed[0][key]); }

So, now you have "33", "Oleg", "Smith" in aaData, which you can access by index:

aaData[0] will give you 33
aaData[1] will give you Oleg, etc

It sounds like you want to be able to handle the case where there is more than one element in the searchObj array. In that case you can loop through all elements of the array and push each of them:

for (var i = 0; i < searchObj.length; i++) {
    aaData.push(searchObj[i].first_name);
}

When there is only one element, only that one element will be pushed.

You can parse the JSON and then loop through the data, inserting each item into your collection array like such:

var parsedData = JSON.parse(responseData);

parsedData.forEach(function (item) {
    arrayCollection.push(item);
}

This one will work on older browsers too:

var parsedData = $.parseJSON(responseData);

$.each(parsedData, function (index, item) {
    arrayCollection.push(item);
}

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