js语法中有 obj.a / obj[a], 都能取到 obj 对象里的 a 值
const getOneObjValue = (oneObject: Object, attributeChain: String, defaultValue = null) => {
if (!oneObject || typeof oneObject !== 'object') {
return null;
}
const result = attributeChain
.replace(/\[/g, '.')
.replace(/\]/g, '')
.split('.')
.filter(item => item)
.reduce((acc, val) => {
if (acc && Object.keys(acc).indexOf(val) > -1) {
acc = acc[val];
return acc;
} else {
return null;
}
}, oneObject);
return result === undefined || result === null ? defaultValue : result;
};
let myObj = {
a: {
b: {
c: 'ccccc',
d: 'ddddd'
},
e: 'eeeee'
},
f: 'fffff'
}
getOneObjValue(myObj, 'a.b.d', '没找到你要的值~')