I read about how to iterate through a multi levels JSON object that contains both object and array in it using recursive technique.
Lets say the object in question is as follow
{
"data":[
{
"Name": "Name1",
"Id": "Id1",
"Prop": {
"isProp":""
"isClass":"Yes"
}
},
{
"Name": "Name2",
"Id": "Id2",
"Prop": {
"isProp":"No"
"isClass":"Yes"
}
},
{
"Name": "Name3",
"Id": "Id3",
"Prop": [
{
"isProp":"Maybe"
"isClass":""
},
{
"isProp":"No"
"isClass": null
},
]
}
]
}
Using the above as example, and if i want to change the empty or null value into a valid string, is below the right way to perform the recursive technique to iterate through the JSON object?
$.ajax(somethingHere).success(function(data){
!(Array.isArray(data)) ? iterateObj(data) : $.each(data, function(){ iterateObj(this) });
});
function iterateObj(data){
for(var key in data){
if (data.hasOwnProperty(key)){
if (!(Array.isArray(data[key]))){
if (!data[key]){
data[key] = "Empty";
}
}
else {
$.each(data, function(){ iterateObj(this) })
}
}
}
}
I tried the above but didn't work. Not sure where is my mistake tho. If possible, i'd like the function above to be able to iterate through any JSON object of any level and with/without object or array in it.
And i read somewhere that using Underscore/Lo-dash's pick/deepClone (not sure if i got it right) makes iteration (through any levels, and to any inner object/array inside the JSON object) much easier, is this true?
Thanks
trampolinewhich allows arbitrary levels of recursion without blowing the Javascript stack.