1

How is it possible to check if a deep nested object containing a value? I want to check if the given object contains for example, a property value that contains "where" :

let data = {
    name: 'Somebody',
    address: {
        city: 'somewhere'
    },
    tags: [{
        id: 5
        name: 'new'
    }]
}
check(data, 'where') // should be true
Aruna
  • 11,959
  • 3
  • 28
  • 42
mjoschko
  • 564
  • 1
  • 7
  • 17

1 Answers1

5

You can use a recursive function as below which is iterating over the keys and checking for the type. If the type is object or array, it will invoke recursive check.

Working snippet:

let data = {
    name: 'Somebody',
    address: {
        city: 'somewhere'
    },
    tags: [{
        id: 5,
        name: 'new'
    }]
};

const check = (obj, text) => {
  var exists = false;
  var keys = Object.keys(obj);
  for(var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var type = typeof obj[key];
    if(type === 'object') {
      exists = check(obj[key], text);
    } else if(type === 'array') {
      
      for(var j = 0; j < obj[key].length; j++) {
        exists = check(obj[key][j], text);
    
        if(exists) {
          break;
        }
      }
      
    } else if(type === 'string') {
      exists = obj[key].indexOf(text) > -1;
    }
    
    if(exists) {
      break;
    }
  }
       
  return exists;
};

console.log(check(data, 'where')); // should be true
Aruna
  • 11,959
  • 3
  • 28
  • 42