Javascript: How to create an object from a dot separated string? -
edit: modifying phrasing since not homework question. people downvoting should ashamed. ;)
i ran potential scenario posed few of employees test question. can think of couple ways solve problem, neither of them pretty. wondering solutions might best optimization tips. here's question:
given arbitrary string "mystr" in dot notation (e.g. mystr = "node1.node2.node3.node4") @ length, write function called "expand" create each of these items new node layer in js object. example above, should output following, given object name "blah":
blah: { node1: { node2: { node3: { node4: {}}}}}
from function call:
mystr = "node1.node2.node3.node4"; blah = {}; expand(blah,mystr);
alternately, if easier, function created set variable returned value:
mystr = "node1.node2.node3.node4"; blah = expand(mystr);
extra credit: have optional function parameter set value of last node. so, if called function "expand" , called so: expand(blah, mystr, "value"), output should give same before node4 = "value" instead of {}.
here's method popped in mind. splits string on dot notation, , loops through nodes create objects inside of objects, using 'shifting reference' (not sure if that's right term though).
the object output
within function contains full object being built throughout function, ref
keeps reference shifts deeper , deeper within output
, new sub-objects created in for-loop.
finally, last value applied last given name.
function expand(str, value) { var items = mystr.split(".") // split on dot notation var output = {} // prepare empty object, fill later var ref = output // keep reference of new object // loop through nodes, except last 1 for(var = 0; < items.length - 1; ++) { ref[items[i]] = {} // create new element inside reference ref = ref[items[i]] // shift reference newly created object } ref[items[items.length - 1]] = value // apply final value return output // return full object }
the object returned, notation can used:
mystr = "node1.node2.node3.node4"; blah = expand(mystr, "lastvalue");
Comments
Post a Comment