views:

194

answers:

3

Ok, so this shouldn't be difficult, however I have encountered weird and bizarra flukes.

I am trying to pack a tree into an array, where each node is something like:

  • title: string-for-display
  • key: id-value
  • children: array of child nodes

the fluke is so strange I can't comprehend it at all: when I try to add a child to a node, I do something like

if(node.children == undefined) {
  node.children = new Array();
}

node.children.push({ title: value, key: key });

this was deleting some previously inserted nodes....so I did some debugging and found that this code:

if(node.children == undefined) {
  node.children = new Array();
}

was at fault, which doesn't make any sense at all - node.children = new Array() shouldn't delete ANYTHING if node.children is undefined......, right?

Am I doing something wrong? if so, how do I pack the tree into an array in Javascript?

+1  A: 

Have you tried the in operator?

if (!("children" in node))
  node.children = [];
orip
+3  A: 

The way you are using the undefined value is not consistent with Javascript standard practices. I'm not sure if this will solve your problem, but try changing you code to

if (typeof(node.children) == 'undefined') { 
  node.children = [];
}

This might actually help. Also, as you can see, using the Array constructor is unnecessary: [] creates a new empty array.

Undefined is not an actual reserved word in Javascript. There is nothing preventing you from setting

undefined = 2;

after which any comparisons to it will behave unpredictably.

levik
+1. OP may not be doing this, but if the code is contained then declaring a variable named undefined should be perfectly fine AFAIK. So the code could be changed to: var undefined; if (node.children === undefined) { node.children = []; }. Of course, this is only useful if you're using the same variable for this purpose in a large body of code. The string comparison has always rubbed me the wrong way though.
Bryan Matthews
+1  A: 

To check if a property exists on an object, use hasOwnProperty

if (!node.hasOwnProperty('children')) {
    node.children = [];
}
nickf