Get object value from the string path

I have found this question which was asked in the Amazon frontend interview, where we are given a nested object or an array of objects or arrays and a string path, we have to implement a function that will return the value at the given path.

Example

get([{ developer: "Tom" }, { count: [0, 1] }], "[1].count[0]");

// 0

In the above example, we are returning the value of the 1st index and the count key’s 0th index.

In JavaScript arrays are also objects, thus we can access the values the same way as we do for objects.

To implement the above solution, we will replace the square brackets with the period operator . and then split the path on the period and return the value at the path.

To get the value, traverse the object and store the value of the current key. Repeat it for each key in the array. Finally, return the value.

const get = (obj, path) => {
  // replace the square brackets with the period operator
  path = path.replaceAll('[', '.');
  path = path.replaceAll(']', '');
  
  // split the keys and get it filtered on the truthy values
  const keys = path.split('.').filter(Boolean);
  
  // create a reference of the input object
  let current = obj;
   
  // traverse the key
  for(let key of keys){
    current = current[key];
    
    // if an invalid key
    // return undefined
    if(current === undefined){
      return undefined;
    }
  }
  
  // return the value
  return current;
};

Test case

Input:
console.log(get({ developer: "Software Engineer" }, "developer"));
console.log(get({ developer: { firstName: "Tom", lastName: "Cruz" } }, "developer.lastName"));
console.log(get([{ developer: "Tom" }, { count: [0, 1] }], "[1].count[0]"));
console.log(get([{ developer: "Tom" }, [0, null]], "[1][1]"));
console.log(get([{ developer: "Tom" }, [0, null]], "[1][3]"));

Output:
'Software Engineer'
'Cruz'
'0'
null
undefined