动态创建JavaScript对象客户端

时间:2014-04-30 04:22:50

标签: javascript json object dynamic

我需要动态创建下面的JavaScript对象,但它过于复杂。

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"}}
    ]
};

它是一个动态的东西,因为我需要动态更改id的值,有时我需要添加更多节点和更多链接,如下所示

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"}}
    ]
};

我想使用JavaScript

创建它
var data = {};
and data.nodes = ?;
and data.links = ?;

不喜欢添加特定的

我的问题是如何创建

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

使用JavaScript,我希望更改idloaded的值,并将其添加到节点信息中,每次我有不同数量的节点和链接。

2 个答案:

答案 0 :(得分:1)

你可以使用一个功能:

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' } }
]

答案 1 :(得分:0)

如果要添加到数组:

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