getByPath.js.flow 1.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @providesModule getByPath
 * @flow
 * @typechecks
 */
'use strict';
/**
 * Get a value from an object based on the given path
 *
 * Usage example:
 *
 *   var obj = {
 *     a : {
 *       b : 123
 *     }
 *   };
 *
 * var result = getByPath(obj, ['a', 'b']); // 123
 *
 * You may also specify the path using an object with a path field
 *
 * var result = getByPath(obj, {path: ['a', 'b']}); // 123
 *
 * If the path doesn't exist undefined will be returned
 *
 * var result = getByPath(obj, ['x', 'y', 'z']); // undefined
 */

function getByPath(root
/*?Object | Error*/
: any, path: Array<string>, fallbackValue?: any): any {
  let current = root;

  for (let i = 0; i < path.length; i++) {
    const segment = path[i]; // Use 'in' to check entire prototype chain since immutable js records
    // use prototypes

    if (current && segment in current) {
      current = current[segment];
    } else {
      return fallbackValue;
    }
  }

  return current;
}

module.exports = getByPath;