blog icon indicating copy to clipboard operation
blog copied to clipboard

不知道父对象是否存在时,如何安全访问对象的子属性?

Open wuxianqiang opened this issue 5 years ago • 0 comments

function safelyGet(obj, path, fallback = undefined) {
  let needle = obj;
  const found = path.every(el => {
    if (needle[el] === undefined) return false;
    needle = needle[el];
    return true;
  });
  return found ? needle : fallback;
}

// Usage
const myObj = {
  user: {
    bio: {
      age: 25
    }
  }
}

const age = safelyGet(myObj, ["user", "bio", "age"]);
console.log(age); // 25

const permissions = safelyGet(myObj, ["user", "auth", "permissions"], "none");
console.log(permissions); // "none"

wuxianqiang avatar Jan 09 '20 02:01 wuxianqiang