2

I am receiving a deeply nested object. I don't know which properties will be present. If I want to get the image, I can't just do this

data.opposite.info.logo.images.s.resized_urls.s,

Imagine this comes from a system where user can leave the logo empty, then my code will break. Do I need to check the existence of properties like this?

if(data.opposite){

   if(data.opposite.info)

     if(data.opposite.info.images)

//...etc
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Jessie Anderson
  • 319
  • 6
  • 13

2 Answers2

1

Use javascript's try { ... } catch(e) { ... } block.

try { 
  url = data.opposite.info.logo.images.s.resized_urls.s; } 
catch(e) { 
  url =  '' 
}

Also loadash.js has a get method that can help you with this

var url = _.get(data, 'opposite.info.logo.images.s.resized_urls.s', '');

this will traverse deep into the object if the path exists and return the 's'. If it is not there, it returns the last argument which is '' in this case.

gmuraleekrishna
  • 3,375
  • 1
  • 27
  • 45
0

I'm trying to get value by scan object: jsfiddle

function getObjByProperty(obj, propertyName) {
  if (obj instanceof Object) {
    if (obj.hasOwnProperty(propertyName)) {
        return obj[propertyName];
    }
    for (var val in obj) {
        if (obj.hasOwnProperty(val)) {
            var result = getObjByProperty(obj[val], propertyName);
            if (result != null) {
                return result;
            }
        }
    }
   } else {
    return null;
  }
 }

 var images = getObjByProperty(data, 'images');
 if (images) {      
  console.log(images);
 }