i have following data.
var data = "a.b.c.d"; //just example can more deep.
- a nested structure string create a.b.c.n
now want create js object data this..
{ "a":{ "b":{ "c":{ , on till given depth. } } } } what have tried
function createhierarchy( obj, group, i){ if(i === group.length){ return obj; } else{ if(obj[group[i]] === undefined) { obj[group[i]] = new object(); } createhierarchy(obj[group[i]], group, ++i); } } problem
this function returning me undefined sending newly created subobject in every recursive call , since newly created object {} , hence final result undefined.
update
i want create object if not exist.for eg : if d exists ill insert value it. else ill create it.
so added @tholle's answer.
if(temp[array[i]] === undefined) temp = temp[array[i]] = {}; else temp = temp[array[i]][name] = value; so kindly suggest way out.
var data = "a.b.c.n"; var array = data.split("."); var result = {}; var temp = result; for(var = 0; < array.length; i++) { temp = temp[array[i]] = {}; } console.log(result);
Comments
Post a Comment