方式一:通過遞歸
// 獲取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獲取深層次屬性,一道很經(jīng)典的面試題纱耻,在此基礎(chǔ)上通過替換[]為.來兼容有[]的情況
ES7可選鏈式調(diào)用 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);
};
// 兼容正則中需要轉(zhuǎn)義的
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]'))