Json String: (response)
{"19":{"id":"19","name":"Product","sku":123,"price":"59.50","cost":"25.00"},"20":{"id":"20","name":"Test","sku":456,"price":"50.00","cost":"40.00"}}
JavaScript Code:
var json = $.parseJSON(response);
var items = new Array();
$.each(json, function(index, value){
items[index] = value.id;
});
console.log(items);
// returns [ , , , , , , , , , , , , , , , , , , , 19, 20 ]
I have a JSON object that’s originally built from a php array and converted using json_encode. When I loop through the object – to build a new array based off some of the values, it has null as all the first items, then the last two has the the actual id.
Any ideas what I’m doing wrong?
This is because you are using an array for
items. When you setitems[19], it needs to set values 0-18 first (these are the “null” values). This is because JavaScript doesn’t have associative arrays, only numeric.Try using an object for
itemsinstead.P.S. The “null” items in the array are actually
undefined.