javascript - Creating a nested JSON object dynamically? -
i there cannot seem functionality going planned.
i have json 'jsondata' contains formula of different terms
"jsondata":{ "a" : "b + c", "b" : "d + e", "d" : "h + i", "c" : "f + g" }
what trying have function pass 1 arguments 'mainitem'(ie. 1 of key in 'jsondata' example a
in 'jsondata'). within function formula json data(for example 'mainitem' , b + c
formula) , check dependency of child component of formula i.e check whether b
, c
have dependency down line in json data. if has dependency added child component parent example if b
have formula in json data. b
added 'mainitem' in child component of parent 'mainitem' a
. @ end of code, get.
{ mainitem : "a", formula : "b+c", childcomponent: { mainitem: "b", formula : "d+e", childcomponent: { mainitem: "d", formula : "h+i" } }, { mainitem: "c", formula : "f+g" }, }
the issue able create parent object. have no idea how create child component parent , if child component have sub child embedded child of child component , on. parent child hierarchy series
function getjson(mainitem) { var json = {}; json['mainitem'] = mainitem; $.each(jsondata, function(key, value){ if(mainitem == key){ json['formula'] = value; } }) }
any insight highly appreciated. thank you.
you need/could write recursive function splits "formula" each composing component/item , check each component/item dependencies.
here solution you: http://jsfiddle.net/mqchen/4x7cd/
function getjson(item, data) { if(!data["jsondata"].hasownproperty(item)) return null; var out = { mainitem: item, formula: data["jsondata"][item] }; // break formula var components = out.formula.split(" "); for(var = 0; < components.length; i++) { var child = getjson(components[i], data); // recursive call childcomponents if(child !== null) { out["childcomponent"] = out["childcomponent"] == undefined ? [] : out["childcomponent"]; out["childcomponent"].push(child); } } return out; } // call getjson("a", data)
note: not consider circular dependencies, i.e. if have a: "b + c", b: "d + a"
.
Comments
Post a Comment