Topic Description

Create a get utility function that takes three parameters:

The get function should recursively navigate the object structure based on the provided path and return the corresponding value if it exists. If the path does not lead to a valid property or the object is undefined/null, it should return the provided defaultValue.

const object = { a: [{ b: { c: 3 } }] };

console.log(get(object, 'a[0].b.c')); // => 3
console.log(get(object, 'a[0][b][c]')); // => 3
console.log(get(object, 'a[100].b.c', 'default')); // => 'default'

Answer


function get(object, pathParam, defaultValue) {
  if (object == null) {
    return defaultValue;
  }

  let count = 0;
  const path = pathParam.split(/[\\.\\[\\]]/)
  console.log('path is an array: ',path)
  const length = path.length;

  while (object != null && count < length) {
    const key = path[count]
    if (key) {
	    object = object[key];
    }
		count++
  }

  
  const result = count && count === length ? object : undefined;
 
  return result === undefined ? defaultValue : result;
}
function get(object, pathParam, defaultValue) {
  if(object == null){
	  return defaultValue
  }
  let index = 0
  const regex = /[.\\[\\]]/g
	const pathArray = pathParam.split(regex)
	console.log('path is an array: ',pathArray)
	const len = pathArray.length
	
	while(index < len && object){
		const key = pathArray[index]
		if(key){
			object = object[key]
		}
		index++
	}
	const result = (index == len && object) ? object : defaultValue
	return result
}