All files / obj find.js

100% Statements 14/14
100% Branches 8/8
100% Functions 1/1
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                              4x 4x 1x   3x 1x     2x   2x   2x 5x 5x 1x   4x     1x     1x  
/**
 * 查找对象路径上的值(简易版)
 * @see [lodash.get](https://lodash.com/docs/4.17.15#get)
 * @method obj/find
 * @param {Object} object 要查找的对象
 * @param {String} path 要查找的路径
 * @return {*} 对象路径上的值
 * @example
 * var $find = require('@spore-ui/kit/packages/obj/find');
 * var obj = {a:{b:{c:1}}};
 * console.info($find(obj,'a.b.c')); // 1
 * console.info($find(obj,'a.c')); // undefined
 */
 
function findPath(object, path) {
  path = path || '';
  if (!path) {
    return object;
  }
  if (!object) {
    return object;
  }
 
  var queue = path.split('.');
  var name;
  var pos = object;
 
  while (queue.length) {
    name = queue.shift();
    if (!pos[name]) {
      return pos[name];
    }
    pos = pos[name];
  }
 
  return pos;
}
 
module.exports = findPath;