Lodash的get方法模拟实现

function get(obj, path, defaultValue = undefined) {
  // 如果path是字符串,则将其转为数组
  path = typeof path === 'string' ? path.split('.') : path;

  // 遍历path数组取出obj中对应的值,如果不存在返回defaultValue
  for (var i = 0; i < path.length; i++) {
    var key = path[i];
    if(Array.isArray(obj) && !Number.isNaN(Number(key))) {
      // 如果obj是数组,且key可以转成数字,则使用索引访问
      key = Number(key);
    }
    if (!obj || !obj.hasOwnProperty(key)) {
      return defaultValue;
    }
    obj = obj[key];
  }
  return obj;
}

// 使用示例
var obj = { a: { b: [{c:1},2] } };

console.log(get(obj, 'a.b.0.c')); // 1
console.log(get(obj, ['a', 'b', 0, 'c'])); // 1
console.log(get(obj, 'a.b.1', 'defaultVal')); // 2
console.log(get(obj, 'a.b.2', 'defaultVal')); // 'defaultVal'
console.log(get(obj, 'a.b.0.d')); // undefined

Mark24

Everything can Mix.