方式一:通过递归
// 获取js深层次属性兼容有[]的情况
function getJsonValue(obj, node) {
if (!obj) {
return null;
}
if (!node) {
return null;
}
let nodes = node.split(".");
let item = nodes[0]
let newObj = obj[item]
if (nodes[0].indexOf('[') > -1) {
let itemArr = item.split("[")
newObj = obj[itemArr[0]]
newObj = newObj[itemArr[1].slice(0, -1)]
}
if (nodes.length == 1) {
return newObj;
}
return getJsonValue(newObj, node.substring(item.length + 1));
}
var a = {
aa: {
aaa: [1, 2, 3]
}
}
console.log(getJsonValue(a, 'aa.aaa[1]'))
参考下面文章后js获取深层次属性,一道很经典的面试题,在此基础上通过替换[]为.来兼容有[]的情况
ES7可选链式调用 console.log(data.user?.address?.street) //undefined
方式二:reduce
String.prototype.replaceAll = function (search, replacement) {
var target = this;
search = escapeRegExp(search)
return target.replace(new RegExp(search, 'g'), replacement);
};
// 兼容正则中需要转义的
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
const safeGet = (o, path) => {
// 只要把[]都替换了就好了嘛
path = path.replaceAll('[', '.')
path = path.replaceAll(']', '')
console.log('path', path)
try {
return path.split('.').reduce((o, k) => o[k], o)
} catch (e) {
return void 666
}
}
var a = {
aa: {
aaa: [1, 2, 3]
}
}
console.log(safeGet(a, 'aa.aaa[1]'))