userBG
userBG

Reputation: 7180

How to build an associative array with jQuery/javascript?

I have a large array in this format:

var cars = [{"brand":"Honda","year":"2002"},{"brand":"Toyota","year":"2000"},{"brand":"Subaru","year":"2009"}];

The array is very large (I made it small for demo purpose) and I want to organize cars of the same brand into an array, so the brand name will be the key for each sub-array, like this:

carsByBrand[ honda[], toyota[], subaru[] ]

I expected it would be straight forward but it's not so. I've tried several variations of the following code, but everytime it returns:

carsByBrand[item.brand] is undefined

 var carsByBrand = [];

   $.each(cars, function(i,item){
     carsByBrand[item.brand].push(item);
    });

    //console.debug(carsByBrand); //uncomment and look at this if you have Firebug

    alert(carsByBrand.length);

I've also tried carsByBrand[item['brand']], why doesn't this work, and how to do it?

jsBin: http://jsbin.com/orafos

Upvotes: 0

Views: 2022

Answers (1)

Thilo
Thilo

Reputation: 262850

carsByBrand[item.brand].push(item);

That will only work if the array for that brand already exists, which it does not unless you initialize it first with an empty array.

Try

   brand = carsByBrand[item.brand];
   if (brand) {
       brand.push(item);
   else {    
       carsByBrand[item.brand] = [item];
   }

Upvotes: 3

Related Questions