类似lodash.get可以按path来取对象的值,同时也支援预设值,如下:

/**
 * Created by milo on 17/3/22.
 */

function deepGet(object, path, defaultValue) {
    return (!Array.isArray(path) ? path.replace(/\[/g, '.').replace(/\]/g, '').split('.') : path)
            .reduce((o, k) => (o || {})[k], object) || defaultValue;
}

var obj = { 'a': [{ 'b': { 'c': 3 } }] };

var result =deepGet(obj, 'a[0].b.c');
console.log(result);
// => 3

result=deepGet(obj, ['a', '0', 'b', 'c']);
console.log(result);
// => 3

result=deepGet(obj, 'a.b.c', 'default');
console.log(result);
// => 'default'

结果:

实现lodash.get功能

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-11
  • 2021-11-18
  • 2021-11-16
  • 2022-01-19
  • 2022-01-15
  • 2021-07-31
猜你喜欢
  • 2021-12-18
  • 2021-09-10
  • 2021-09-30
  • 2021-10-26
  • 2021-08-18
  • 2022-01-21
相关资源
相似解决方案