Education

Implement lodash's `.get` method

In this article, We will try to implement basic funtionality of lodash's `.get` method

Implement lodash's `.get` method

In this article, we will try to implement basic funtionality of lodash's .get method. We will impolement getValue function that will take an array of Object and a path string as arguments. It will returns the value of path in object.

** For Example**:

const value = {
  a: {
    b: {
      c: {
        d: 'value of d',
      },
    },
  },
  x: 'value of x',
}
 
getValue(obj, 'a.b.c.d')
output: 'value of d'
getValue(obj, 'a.b.c')
output: {
  d: 'value of d'
}
getValue(obj, 'a.b.x.d')
output: undefined
getValue(obj, 'x');
output: value of x
getValue(obj, 'z')
output: undefined

What is lodash _.get() ?

_.get(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

** Arguments of lodash's .get method **

object (Object): The object to query.
path (Array|string): The path of the property to get.
[defaultValue] (*): The value returned for undefined resolved values.
Returns
Returns the resolved value.

Lets Implement getValue() function

Before implementation we are going to make few assumptions.

  • getValue() will not access value in array

Javascript Implementation

const obj = {
  a: 'a',
  b: {
    c: {
      d: {
        e: [
          {
            x: 'x',
          },
        ],
      },
    },
  },
}
 
function getValue(obj, path) {
  const keysArray = path.split('.')
  let newobj = JSON.parse(JSON.stringify(obj))
  for (let i = 0; i < keysArray.length; i++) {
    if (typeof newobj[keysArray[i]] === undefined) {
      return newobj[keysArray[i]]
    }
    newobj = newobj[keysArray[i]]
  }
  return newobj
}
 
console.log(getValue(obj, 'a')) // "a"
 
console.log(getValue(obj, 'z')) // undefined
 
console.log(getValue(obj, 'a.z')) // undefined
 
console.log(getValue(obj, 'b.c.d')) // {e}