Design & Download
Your JS Library
in Seconds!!!

Snippet: pull() - Get The Value At a Specific Path

Written by Christopher West (cwest) on July 20, 2016.
Retrieve the value found at a given path within an object.
function pull(obj, path, opt_noErrorDefault) {
  path = typeOf(path, 'String') ? path.split('.') : path;
  for (var doError = arguments.length < 3, i = 0, l = path.length; i < l; i++) {
    if (obj != undefined && path[i] in Object(obj)) {
      obj = obj[path[i]];
    }
    else if (doError) {
      throw new Error('There is no value at "' + slice(path, 0, i + 1).join('.') + '".');
    }
    else {
      return opt_noErrorDefault;
    }
  }
  return obj;
}

pull(...) API Documentation

Retrieve the value found at a given path within an object.

Parameters

  1. obj {*}:
    The object or primitive to get the value from.
  2. path {Array|string}:
    The path to search. If a string is given it will be split on the dots (.).
  3. opt_noErrorDefault {*}:
    Optional. If not specified and the path doesn't exist an error will be thrown. If specified and the path doesn't exist this value will be returned.

Returns

The value found at path. If the path doesn't exist and opt_noErrorDefault is specified, that value will be returned.

Example

console.log(YourJS.pull('Cool!', 'length'));  // -> 5
console.log(YourJS.pull(['Cool!'], 'length'));  // -> 1
console.log(YourJS.pull(['Cool!'], '0.length'));  // -> 5
console.log(YourJS.pull(['Cool!'], '1.length'));  // -> Error:  There is no value at "1.length".