开发者

Looking for a less verbose way of creating hierarchical data in a multidimensional object

If I w开发者_如何学运维ant to create a new node in a multidimensional object I have to check that the parent objects exist before adding it. eg

if(typeof root_object["object1"] == "undefined")
    root_object["object1"] = [];
if(typeof root_object["object1"]["object2"] == "undefined")
    root_object["object1"]["object2"] = [];
root_object["object1"]["object2"]["object3"] = something_or_other;

Is there an easier less verbose way of achieving this?


Javascript won't do this for you automatically, but you can write a function that does it:

function add_hier(obj,path,value) {
  var n=path.length;
  for (var i=0; i<n-1; ++i) {
    var field = path[i];
    if (!(field in obj)) { obj[field] = []; }
    obj = obj[field];
  }
  obj[path[n-1]] = value;
}

add_hier(root_object, ["object1","object2","object3"], something_or_other);

(Danger: completely untested code; may consist entirely of bugs, syntax errors, and radioactive waste. Use with caution.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜