2

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.

2 Answers 2

1

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

0

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);

1 Comment

Thanks for your reply.instead of add information.I need to change the id and loaded dynamic...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.