Michael Bates
Michael Bates

Reputation: 1934

Javascript Multidimensional Array/Hashtable

storeChildren : function(coreid, data) {
  $.each(data, function(id, type) {
    $.core.children[coreid] = {};
    $.core.children[coreid]['id'] = id;
    $.core.children[coreid]['type'] = type;
  });
}

($.core.children is an object)

I want the resulting array/object (I prefer objects) to look like this (excuse my PHP pseudocode):

array(coreid => array(id=>type, id=>type, id=>type));

I know I am overwriting $.core.children[coreid] each time I run the loop I just don't know how to fix it.

Upvotes: 1

Views: 414

Answers (2)

jamesmortensen
jamesmortensen

Reputation: 34038

init: function() {
    $.core.children = []; // instantiate array
},

storeChildren : function(coreid, data) {

    $.each(data, function(id, type) {
        $.core.children[coreid] = {id : type};
    });
}

Instantiate the object elsewhere in your code, then you won't kill the associative array/object each time. The above example also uses an object inside your array instead of an array, the result, in JSON notation, looks as follows:

[ {key,value} , {key,value} , {key,value} , ...]

The coreid is the index of the array.

Upvotes: 0

dfreeman
dfreeman

Reputation: 2834

If all your 'id's are unique, the following should work; is this what you're after?

storeChildren : function(coreid, data) {
  $.core.children[coreid] = {};
  $.each(data, function(id, type) {
    $.core.children[coreid][id] = type;
  });
}

Upvotes: 2

Related Questions