Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
there is no C like multidimensional arrays in JS ,but you can put arrays in other arrays. –  mpm Mar 1 at 20:06
    
At least try to read the manual first... –  inf3rno Mar 1 at 20:08
add comment

1 Answer

up vote 1 down vote accepted

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) );
share|improve this answer
    
Thank you for your explanations, it is very interesting and it works with your code. –  jlafforgue Mar 4 at 17:04
    
Glad it was of some use. I'd be happy if you'd accept my answer. –  mrhobo Mar 4 at 17:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.