ES6 :Vanila JS 中只有一行(如果找不到则返回 null 而不是给出错误):
'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)
或者例如:
'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})
使用可选链接运算符 :
'a.b.c'.split('.').reduce((p,c)=>p?.[c], {a:{b:{c:1}}})
对于可立即使用的函数,它也能识别假、0 和负数,并接受默认值作为参数:
const resolvePath = (object, path, defaultValue) => path
.split('.')
.reduce((o, p) => o ? o[p] : defaultValue, object)
使用示例:
resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1
奖金 :
要 设置 路径(由@rob-gordon 请求),您可以使用:
const setPath = (object, path, value) => path
.split('.')
.reduce((o,p,i) => o[p] = path.split('.').length === ++i ? value : o[p] || {}, object)
例子:
let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}
使用 [] 访问数组 :
const resolvePath = (object, path, defaultValue) => path
.split(/[\.\[\]\'\"]/)
.filter(p => p)
.reduce((o, p) => o ? o[p] : defaultValue, object)
例子:
const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"][\'0\'].c') => 1