javascript - Saving nested json object path to a variable via recursion -
is there way save "path" of json object variable? is, if have this:
var obj = {"mattress": { "productdelivered": "arranged retailer", "productage": { "year": "0", "month": "6" } } };
how can loop through , save each key node name variable? eg. (i need in format): mattress[productdelivered], mattress[productage][year], mattress[productage][month]
i have got partly there in fiddle http://jsfiddle.net/4cewf/ can see in log, year , month don't separated append array well. know because of looping have going on i'm stuck on how progress data format require. flow have set in fiddle emulating need.
is there way haven't considered this?
try
var obj = { "mattress": { "productdelivered": "arranged retailer", "productage": { "year": "0", "month": "6" } } }; var array = []; function process(obj, array, current){ var ikey, value; for(key in obj){ if(obj.hasownproperty(key)){ value = obj[key]; ikey = current ? current + '[' + key + ']' : key; if(typeof value == 'object'){ process(value, array, ikey) } else { array.push(ikey) } } } } process(obj, array, ''); console.log(array)
demo: fiddle
Comments
Post a Comment