JS中搜检内嵌对象是不是存在

有以下多层嵌套的对象:

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));
}

如果有更好的体式格局,迎接补充😂。

    原文作者:crazyitcoder
    原文地址: https://segmentfault.com/a/1190000019286747
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞