林秀栋的技术博客

如何访问对象中暂未定义的属性

文章来源

对于一个对象

const user = {
    id: 101,
    email: 'jack@dev.com',
    info: {
        name: 'Jack',
        address: {
            line1: 'westwish st'
        }
    }
}

当访问其中的user.info.name时,若info不存在,则会报错

Cannot read property ‘name’ of undefined

一般可以采用这种写法

const name = user && user.info ? user.info.name : null
// 或
const name = user && user.info && user.info.name

此时若层级较深写起来会很麻烦

下面是一些其他方法

Oliver Steele的嵌套对象访问模式

const name = ((user || {}).info || {}).name;

缺点是你不能使用此技巧访问嵌套数组

使用数组Reduce访问嵌套对象

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

注意: reduce() 对于空数组是不会执行回调函数的。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

var numbers = [6, 2, 12, 4];
 
function getSum(total, num) {
    return total + num;
}
function myFunction() {
    const result = numbers.reduce(getSum, 0);
}

myFunction()  // result 24
const getNestedObject = (nestedObj, pathArr) => {
    return pathArr.reduce((obj, key) =>
        (obj && obj[key] !== 'undefined') ? obj[key] : null, nestedObj);
}

// 将对象结构作为数组元素传入
const name = getNestedObject(user, ['personalInfo', 'name']);

// 要访问嵌套数组,只需将数组索引作为数组元素传入。.
const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);
// 这将从 addresses 中的第一层返回 city

babel的optional chainning

文档

npm install –save-dev @babel/plugin-proposal-optional-chaining

.babelrc

{
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}

use

const obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
};

const baz = obj?.foo?.bar?.baz; // 42

const safe = obj?.qux?.baz; // undefined