var obj = {
a: {
b: {
c: 1
}
}
}
想用'a.b.c'
能直接访问到1
怎么写 不是用obj.a.b.c 也不是用obj'a'['c'],
用个函数来转换还是
function getPropByPath(obj, path) {
let tempObj = obj;
path = path.replace(/[(w+)]/g, '.$1');
path = path.replace(/^./, '');
let keyArr = path.split('.');
let i = 0;
for (let len = keyArr.length; i < len - 1; ++i) {
if (!tempObj) break;
let key = keyArr[i];
if (key in tempObj) {
tempObj = tempObj[key];
} else {
return null
//break;
}
}
return tempObj ? tempObj[keyArr[i]] : null
}
getPropByPath(obj, 'a.b.c') // 1
getPropByPath(obj, 'a[b][c]') // 1