有以下多层嵌套的对象:
var obj = {
l1: {
l2: {
l3: "Hello World"
}
}
}
要领1:
var r = (((obj || {}).l1 || {}).l2 || {}).l3;
或
var r = obj.l1 && obj.l1.l2 && obj.l1.l2.l3
要领2:
let delve = (obj, key) => (key.split('.').map(p => (obj = obj && obj[p])), obj);
console.log(delve(obj, 'l1.l2.l3')); // Hello World
要领3:
function checkNested(obj, key, ...rest) {
if (obj === undefined || obj === null) return false;
if (rest.length == 0 && obj.hasOwnProperty(key)) return true;
return checkNested(obj[key], ...rest);
}
console.log(checkNested(obj, 'l1', 'l2', 'l3')); // true
要领4:
function validChain(obj, ...keys) {
return keys.reduce((obj, key) => (obj || {})[key], obj) !== undefined
}
console.log(validChain(obj, 'l1', 'l2', 'l3')); // true
要领5:
function objHasKeys(obj, keys) {
var next = keys.shift();
return obj[next] && (! keys.length || objHasKeys(obj[next], keys));
}
如果有更好的体式格局,迎接补充😂。