I have a json object which is variable (with possibly infinite sub-structures):
var myObject={
s1:{
s2:'2',
s3:'3'
},
s4:'4',
s5:{
s6:undefined
},
s7:'7'
};
I would like to find the first undefined member and to return it's reference, to be able to modify it anytime (by event triggered functions)
function findFirstUndefined(obj){
for (var key in obj){
if (typeof(obj[key]) === 'object'){
var recursion=findFirstUndefined(obj[key])
if (recursion!==false){
return recursion;
}
}
else if (obj[key]===undefined){
return obj[key];
}
}
return false;
}
But it doesn't return the reference of the member, but it's value:
var subObj=findFirstUndefined(myObject);
subObj="my updated cool var!!";
doesn't modify the object.
I found that a library like JsonPath could do the trick, but it seems to me kind of heavy for such a simple task.
Wouldn't it exists an elegant way to do so? Thank's!
JS doesn't do that. You could instead return a function that will assign to the missing entry?
return function(v) { obj[key] = v; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With