# 27.根据key获取Object里面的值
// 例子
const obj = {
a: [{ c: 3 }, { d: 4 }],
b: {
c: 4,
},
};
console.log(getObjectPath(obj, "a.0.c")); // 输出: 3
console.log(getObjectPath(obj, "a[1].d")); // 输出: 4
console.log(getObjectPath(obj, "b.c")); // 输出: 5
console.log(getObjectPath(obj, "b.c.d.b")); // 输出: 5
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
答案:
function getObjectPath(obj, path){
const keys = path.replace(/\[(\w+)\]/, ".$1").split('.')
return keys.reduce((acc, key)=>{
if(typeof(acc) === 'object' && acc !== null){
if(key in acc){
return acc[key];
} else {
return undefined;
}
}
return undefined
}, obj)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13