atekul
atekul

Reputation: 139

dynamically create a JavaScript object client side

I need to create the JavaScript object below dynamically, but it's too complex.

var data = {
    "nodes":[
        {"id":"n1", "loaded":true, "style":{"label":"Node1"}},
        {"id":"n2", "loaded":true, "style":{"label":"Node2"}},
        {"id":"n3", "loaded":true, "style":{"label":"Node3"}}
    ],
     "links":[
        {"id":"l1","from":"n1", "to":"n2", "style":{"fillColor":"red", "toDecoration":"arrow"}},
        {"id":"l2","from":"n2", "to":"n3", "style":{"fillColor":"green", "toDecoration":"arrow"}},
        {"id":"l3","from":"n3", "to":"n1", "style":{"fillColor":"blue", "toDecoration":"arrow"}}
    ]
};

and its a dynamic thing because I need to change the value of the id dynamically and sometimes I need to add more nodes and more links like below

var data = {
    "nodes":[
        {"id":"n1", "loaded":true, "style":{"label":"Node1"}},
        {"id":"n2", "loaded":true, "style":{"label":"Node2"}},
        {"id":"n3", "loaded":true, "style":{"label":"Node3"}},
        {"id":"n3", "loaded":true, "style":{"label":"Node3"}},
    ],
     "links":[
        {"id":"l1","from":"n1", "to":"n2", "style":{"fillColor":"red", "toDecoration":"arrow"}},
        {"id":"l2","from":"n2", "to":"n3", "style":{"fillColor":"green", "toDecoration":"arrow"}},
        {"id":"l3","from":"n3", "to":"n1", "style":{"fillColor":"blue", "toDecoration":"arrow"}}
        {"id":"l3","from":"n3", "to":"n1", "style":{"fillColor":"blue", "toDecoration":"arrow"}}
        {"id":"l3","from":"n3", "to":"n1", "style":{"fillColor":"blue", "toDecoration":"arrow"}}
    ]
};

I want to create it using JavaScript

var data = {};
and data.nodes = ?;
and data.links = ?;

Not like add a specific

my question is how can I create

{"id":"n1", "loaded":true, "style":{"label":"Node1"}},

using JavaScript and I want change the value of id and loaded and put it into that nodes information also, each time I have different number of nodes and links.

Upvotes: 2

Views: 138

Answers (2)

user1636522
user1636522

Reputation:

You could use a function :

function makeNode(n, loaded) {
    return {
        id: 'n' + n, 
        loaded: loaded || false, 
        style: { label: 'Node' + n }
    };
}
data.nodes.push(makeNode(1));
data.nodes.push(makeNode(2, false));
data.nodes.push(makeNode(3, true));
// data.nodes
[
    { id: 'n1', loaded: false, style: { label: 'Node1' } },
    { id: 'n2', loaded: false, style: { label: 'Node2' } },
    { id: 'n3', loaded: true,  style: { label: 'Node3' } }
]

Upvotes: 1

Joshua Nelson
Joshua Nelson

Reputation: 581

If you want to add to an array:

var x = {"id":"n3", "loaded":true, "style":{"label":"Node3"}}; //the thing you want to add
data.nodes.push(x);

Upvotes: 0

Related Questions