实现深层对象属性访问

输入对象以及属性名,获得属性值
【实现深层对象属性访问】eg:输入:data, 'a/b/c'

const data = https://www.it610.com/article/{ a: { b: { c:1, d:2 } } }

输出:1
方法1:while遍历
function findObjectValue(object, attribute) { let arr = attribute.split('/') let i = 0 while (arr[i]) { object = object[arr[i]] i++ } return object }const data = https://www.it610.com/article/{ a: { b: { c:1, d:2 } } } console.log(findObjectValue(data,'a/b/c'))

方法2:eval拼贴字符串
拼出来就是这样的,temp['a']['b']['c']
const findObjectValue = https://www.it610.com/article/(data, attr) => { let temp = data; return eval(`temp['${attr.split('/').join(`']['`)}']`); }const data = https://www.it610.com/article/{ a: { b: { c:1, d:2 } } } console.log(findObjectValue(data,'a/b/c'))

    推荐阅读