0

I'm trying to create a multi-dimensional array.

My assumption that the following structure stuff['mykey1']['mykey2']['mykey3'] can be interpreted as stuff is an array of two-dimensional arrays. And stuff['mykey1'] will return me a two dimensional array with following keys ['mykey2']['mykey3']

I try to create this structure like so:

var stuff = null;

if(stuff === null) 
{
    stuff = []; // stuff is []
}

if(stuff[userId] === undefined)
{
    stuff[userId] = [];  // stuff is [undefined, undefined, undefined, 888087 more...]
}

if(stuff[userId][objectId] === undefined)
{
    stuff[userId][objectId] = [];
} 

However, when I look at stuff array as I step through, I see that after stuff[userId] = []; stuff array is [undefined, undefined, undefined, 888087 more...]

I'm expecting [888087, []]

Where do the undefined values come from?

dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

4 Answers4

4

Where do the undefined values come from?

You are using Arrays, not objects. If you add a numerical property on an Array object, it's length will be updated and the other indices stay unitialized (sparse array), but are displayed as undefined (see What is "undefined x 1" in JavaScript?).

Instead, use normal objects, where numerical properties have no special behavior:

var stuff = null;

if(stuff === null) 
{
    stuff = {}; // stuff is an empty object
}

if(stuff[userId] === undefined)
{
    stuff[userId] = {};  // stuff is now enriched with one property
}

if(stuff[userId][objectId] === undefined)
{
    stuff[userId][objectId] = {}; // or maybe you really want an array here?
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Its because of usage of arrays. The length of the remainin elements is made undefined. For example if a(1) is specified, a(0) will be undefined

LPD
  • 2,833
  • 2
  • 29
  • 48
0

You are trying to create associative arrays, and in JavaScript this is done with... objects, not arrays!

So at each step you need to use {} instead of [] to create the next level. And you need to use a for...in loop to iterate through the keys.

For more details, search the Web for JavaScript associative arrays". For example:

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

Christophe
  • 27,383
  • 28
  • 97
  • 140
0

The question is long answered, but I want to chip in with this shorthand, that really makes it more compact and readable:

stuff = stuff || {};

// if stuff is already defined, just leave it be. If not (||), define it as object

stuff[userId] = stuff[userId] || {};

// if stuff[userId] is already defined, define it as self (let it be unchanged). If not defined ( the || -signs ), define it as object.

stuff[userId][objectId] = stuff[userId][objectId] || {};

// and so on :)