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.
Jason Aller
3,66028 gold badges43 silver badges40 bronze badges
asked Apr 30, 2014 at 4:22
atekul
1391 gold badge2 silver badges10 bronze badges
2 Answers 2
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' } }
]
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Apr 30, 2014 at 4:28
Joshua Nelson
5812 silver badges10 bronze badges
1 Comment
atekul
Thanks for your reply.instead of add information.I need to change the id and loaded dynamic...
lang-js