1

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.

2
  • there is no C like multidimensional arrays in JS ,but you can put arrays in other arrays. Commented Mar 1, 2014 at 20:06
  • At least try to read the manual first... Commented Mar 1, 2014 at 20:08

1 Answer 1

1

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) );
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your explanations, it is very interesting and it works with your code.
Glad it was of some use. I'd be happy if you'd accept my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.