Vegan Sv
Vegan Sv

Reputation: 335

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, e.g.

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].

Upvotes: 0

Views: 108

Answers (3)

user3724182
user3724182

Reputation:

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

Upvotes: 1

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20399

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.

Upvotes: 1

Vitaliy Tsvayer
Vitaliy Tsvayer

Reputation: 773

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

Upvotes: 2

Related Questions