jlafforgue
jlafforgue

Reputation: 287

Create multidimensional array in javascript

I would like to create a multidimensional javascript array like this :

array('cats' => array(
    'cat_1' => array(1, 2, 3 ...)
    ), array(
    'cat_2' => array(....

I would like to add/remove "cat_id" and "tag_id" according to my variables...

var filter = {cats : [[]]};

function generateArray(cat_id, tag_id, add = true){
  if(add == true)
    filter.cats = [cat_id];
    filter.cats[cat_id].push(tag_id);
  } else {
    //How to delete record the tag_id ?
    //filter[cats][cat_id].(tag_id);
  }
  return filter;
}

generateArray(1, 1, true);
generateArray(2, 2, true);
generateArray(2, 3, true); etc...

I have this error message :

undefined is not object (evaluating filter.cats[cat_id].push

What's wrong ? Thanks in advance.

Upvotes: 1

Views: 133

Answers (1)

Lodewijk Bogaards
Lodewijk Bogaards

Reputation: 19987

The problem in this code:

filter.cats = [cat_id];
filter.cats[cat_id].push(tag_id);

is that in the first line you set filter.cats to become an array with one element cat_id (on index 0). Then in the second line you try to access an element in that array with the index cat_id (not the value cat_id) which does not exists or is a number when cat_id is zero. Once you try to use the element as an object (by calling push on it) you get this error.

Instead of those two lines you could write

if (typeof filter.cats[cat_id] == 'undefined') 
  filter.cats[cat_id] = [tag_id]; // initialize element as an array object
else
  filter.cats[cat_id].push(tag_id);  // already initialized, so push

Here is some code to give you an example of how you may achieve your goal:

function addCatTag(cats, cat_id, tag_id) {
    var cat = cats[cat_id];
    if (typeof cat == 'undefined') {
        cats[cat_id] = [tag_id];
    } else {
        cat.push( tag_id );
    }
}

function removeCatTag(cats, cat_id, tag_id) {
    var cat = cats[cat_id];
    if (typeof cat != 'object') 
        return;
    var tag_idx = cat.indexOf(tag_id);
    if (tag_idx >= 0) {
      cat.splice(tag_idx, 1);
    }       
}

var cats = {};
addCatTag(cats, 'felix', 1);
addCatTag(cats, 'felix', 2);
addCatTag(cats, 'fluffy', 1);
removeCatTag(cats, 'felix', 2);

alert( JSON.stringify(cats) );

Upvotes: 1

Related Questions