Javascript returns only the parent object that contains the special property

Suppose I have the following object:

var Obj = {
             a: {
                   name: 'X',
                   age: 'Y',
                   other: {
                             job: 'P',
                             location: {
                                          lat: XX.XXXX,
                                          lng: YY.YYYYY,
                                          .........
                                       }
                          }
                }
          };

My goal: I need a method that checks for existence keyand returns its immediate parent for any level of nesting.

Example If I search lat, this method will return an object location; if I search job, it will return other, etc.

Please, help. Thank....

+3
source share
2 answers

Try the following:

function findObjectWithProperty(obj, term){
    if (typeof obj == 'object'
        && Object.prototype.toString.call(obj) !== '[object Array]'){
        for(var prop in obj){
            if (obj.hasOwnProperty(prop)){
                if (prop==term)
                    return obj;
                var result = findObjectWithProperty(obj[prop], term);
                if (result != null)
                    return result;
            }
        }
    }
    return null;
}

Using:

var location = findObjectWithProperty(Obj, 'lat');
var other = findObjectWithProperty(Obj, 'job');
+3
source

I have no idea to write a general function for this problem, for example Reflection in C #, but this function can help, although it is not general.

//Object.
var Obj = {
             a: {
                   name: 'X',
                   age: 'Y',
                   other: {
                             job: 'P',
                             location: {
                                          lat: 31.88,
                                          lng: 71.88

                                       }
                          }
                }
          };


function getParentObject(key,obj){  
  switch(key){
    case "lat" || "lng":   return obj.a.other.location; break;
    //write other cases...
    default:return obj;
  }
}


//Call
var lng = getParentObject("lat",Obj).lng;
+1
source

All Articles