0

Here is some code I have:

// "iterable" is a Map
iterable.forEach((definition, schemaKey) => {
  let keyToGet = schemaKey.split('.');
});

keyToGet contains a list of nested keys I want to get in sorted sequence. That is, if I have a user object,

{
  profile: {
    name: { full: "Cat Man" }
  }
}

And I want to access profile.name.full using ['profile', 'name', full]. Is this possible to get the value using this list of values?

corvid
  • 10,733
  • 11
  • 61
  • 130
  • `Is this possible to get the value using this list of values?` Yes, of course it is. You'd use the bracket notation to get each property in turn. – Matt Burland Nov 02 '15 at 18:16
  • 3
    Possible duplicate of [JavaScript object: access variable property by name as string](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string) or maybe [Accessing nested JavaScript objects with string key](http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Matt Burland Nov 02 '15 at 18:18

1 Answers1

1

You could do a recursive function that travels down the object if the key is found, finally returning the value if it reaches the end of the array. This returns a -1 if a key is not found:

function getFromArr(obj, arr){
 function travelDown(current,index){
     if(current.hasOwnProperty(arr[index])){
         if(index+1 == arr.length){
             return current[arr[index]]
            }else{
             return travelDown(current[arr[index]], index+1)
            }
        }else{
         return -1;
        }
    }
    return travelDown(obj, 0)
}

var obj ={
  profile: {
    name: { full: "Cat Man" }
  }
}
console.log(getFromArr(obj,["profile", "name", "full"])) // Cat Man
console.log(getFromArr(obj,["profile", "name"])) // {full: "Cat Man"}
console.log(getFromArr(obj,["profile", "name", "nonexistant"])) // -1
juvian
  • 15,875
  • 2
  • 37
  • 38