Tono Nam Tono Nam - 7 months ago 19
Javascript Question

Create tree like structure in javascript

How can I have a reference to an object in javascript? I have the following code:

// define nodes
var NodeA = new Object();
var NodeB = new Object();

NodeA = {
name: "A",
children: [
NodeB
]
}

NodeB = {
name: "B",
children: []
};

var test = NodeA.children[0].name;
// How can I make test = "A" ??? <----------------
alert(test);


I know that if I create NodeB before creating NodeA it will solve my problem.

Answer

You can use Object.assign to assign properties to NodeB instead of setting NodeB to be a reference to a entirely new object:

var NodeB = {};

var NodeA = {
    name: "A",
    children: [
        NodeB
    ]
}

Object.assign( NodeB, {
    name: "B",
    children: []
} );

var test = NodeA.children[0].name;
alert(test);

Note that for Internet Explorer of Object.assign support you would need to use the Polyfill. You could also just assign the properties to the existing object instead of using object literal notation to create a new one:

var NodeB = {};

var NodeA = {
    name: "A",
    children: [
        NodeB
    ]
}

NodeB.name = "B";
NodeB.children = [];

var test = NodeA.children[0].name;
alert(test);