dzm
dzm

Reputation: 23544

Building javascript array but has null values

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?

Upvotes: 2

Views: 184

Answers (4)

Guffa
Guffa

Reputation: 700372

As you are using the index from the object, you are creating a sparse array. The object has properties named "19" and "20", and as you use those as the index in the array, that's where you will get the values from the properties.

If you want to pack the items from the beginning of the array, just push them:

$.each(json, function(index, value){
  items.push(value.id);
});

Result in items:

[ "19", "20" ]

Upvotes: 2

jbabey
jbabey

Reputation: 46647

From MDN:

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the array will grow to a size large enough to accommodate an element at that index, and the engine will update the array's length property accordingly:

You are setting array[19] to a value, so array[0-18] become undefined.

To fix this problem, declare items as an object instead, which can have numerical properties assigned without automatically populating the lower ranges.

Upvotes: 0

Chris
Chris

Reputation: 769

You could also change the JSON response to an array, if possible:

[
  {"id":"19","name":"Product","sku":123,"price":"59.50","cost":"25.00"},
  {"id":"20","name":"Test","sku":456,"price":"50.00","cost":"40.00"}
]

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227270

This is because you are using an array for items. When you set items[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 items instead.

var items = {};

$.each(json, function(index, value){
  items[index] = value.id;
});

console.log(items); // {19: 19, 20: 20}

P.S. The "null" items in the array are actually undefined.

Upvotes: 2

Related Questions