Design & Download
Your JS Library
in Seconds!!!

Snippet: checkPath() - Checks For A Given Path In An Object

Written by Christopher West (cwest) on February 04, 2017.
Determine if a path actually exists within an object.
function checkPath(o, path, opt_returnDeepestPath) {
  if ('string' == typeof path) {
    path = path.split('.');
  }
  for (var k, i = 0, l = path.length; i < l && (k = path[i]) in o; i++) {
    o = o[k];
  }
  return opt_returnDeepestPath ? path.slice(0, i) : i == l;
}

checkPath(...) API Documentation

Determine if a path actually exists within an object.

Parameters

  1. o {*}:
    The object or primitive for which the path should be checked.
  2. path {Array|string}:
    The path to search. If a string is given it will be split on the dots (.).
  3. opt_returnDeepestPath {*}:
    Optional. Defaults to false. If true the returned value will be the deepest path found matching the path passed.

Returns

If opt_returnDeepestPath is true-ish an array will be returned indicating the deepest path found matching the path that was passed. Otherwise true will be returned if the actually exists, but if it doesn't exist false will be returned.

Example

console.log(YourJS.checkPath('Cool!', 'join'));                         // -> false
console.log(YourJS.checkPath(['Cool!'], 'join'));                       // -> true
console.log(YourJS.checkPath({ a: { b: 'c' }, d: 3 }, 'a.b.c'));        // -> false
console.log(YourJS.checkPath({ a: { b: 'c' }, d: 3 }, 'a.b.c', true));  // -> ['a', 'b']