0

I would like to split the str (dot seperated) and look inside an object tree, if the values exist.

To keep it simple, I have just create a simple object, but I would like it to be a deep search.

I just need the logic not necessary a working code, just a direction on what I need to do inside the exists to, check recursebly if person.name.first does exist with a boolean value true || false to be returned as the final answer.

var str = "person.name.first";

var arr = {
  person: {
    name: {'first':true ,'last' : true },
    age : true
  }
}

function exists(){
   ...
}
exists(str,arr);//true === exists, false === does not exist
hsz
  • 148,279
  • 62
  • 259
  • 315
Val
  • 17,336
  • 23
  • 95
  • 144

1 Answers1

2

Just try with:

function exists(str, arr) {
  var parts = str.split('.');
  for (var i = 0; i < parts.length; i++ ) {
    if (arr.hasOwnProperty(parts[i])) {
      arr = arr[parts[i]];
    } else {
      return false;
    }
  }
  return true;
}
hsz
  • 148,279
  • 62
  • 259
  • 315