简体   繁体   中英

adding objects into an existing object

I need to load an external JSON file using a d3.json function which for eg. has this format

{"pole":[{"name": "p1"}, {"name":"p2"}]}

In the main file, I would have

var MainData ={}; d3.json("url", function(graph){MainData[graph] = graph;});

gives me the external JSON object pushed inside MainData. But I would lie to be able to access it as MainData.pole

Also I would like to load multiple JSON files and push them into the same MainData file.

I am new to JS and I would very much appreciate help.

 var MainData ={}; d3.json("url", function(graph){MainData[graph] = graph;}); 

gives me the external JSON object pushed inside MainData.

Well, sort of, but it's got a really awkward property name, most likely [object Object] , because when you use brackets notation like that, the property name within the brackets is given as a string (for now; ES6 adds Symbol s), so any non-string you put there will be turned into a string. The default result of calling toString on a plain object is [object Object] .

But I would lie to be able to access it as MainData.pole

Assuming d3.json parses it for you before giving it to you, then:

var MainData ={};
d3.json("url", function(graph) { 
    MainData.pole = graph.pole;
});

If you're expected to parse it yourself (which seems unlikely), then:

var MainData ={};
d3.json("url", function(graph) { 
    MainData.pole = JSON.parse(graph).pole;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM