实现lodash.get功能

时间:2022-03-16 18:10:11
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'