fe-notes icon indicating copy to clipboard operation
fe-notes copied to clipboard

实现 lodash 中 get 方法

Open Inchill opened this issue 4 years ago • 0 comments

lodash 中的这个方法是用于获取一个变量里的值的,因为很多时候通过点式访问很可能报错,所以希望对路径不存在的返回默认值。

function _get(obj, keys, defaultVal) {
    let lists
    if (Array.isArray(keys)) {
        lists = keys
    } else {
        lists = keys.replace(/\[/g, '.').replace(/\]/g, '').split('.') // 字符串直接根据 . 分割为数组
    }

    let ret = lists.reduce((acc, curKey) => {
        return (acc || {})[curKey] // 重点是利用好这个 acc 累积器,当属性不存在的时候返回的是 undefined
    }, obj)
    return ret || defaultVal
}

var obj = {
  a: [
    {
      b: {
        c: 3,
      },
    },
  ],
  e: {
    f: 1,
  },
};

console.log(_get(obj, 'e.f')); // 1
console.log(_get(obj, ['e','f'])) // 1
console.log(_get(obj, 'a.x')); // undefined
console.log(_get(obj, 'a.x', '--')) // -- 
console.log(_get(obj, 'a[0].b.c')) // 3 => 'a.0.b.c' => ['a', '0', 'b', 'c']
console.log(_get(obj, ['a', 0, 'b', ,'c'])) // 3

Inchill avatar Feb 23 '22 12:02 Inchill