Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript return member of an object by reference

Tags:

javascript

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!

like image 402
Sami Avatar asked Feb 07 '26 01:02

Sami


1 Answers

JS doesn't do that. You could instead return a function that will assign to the missing entry?

return function(v) { obj[key] = v; };
like image 110
DrC Avatar answered Feb 08 '26 14:02

DrC