困っていた事
- ネストの深いオブジェクトのプロパティにアクセスする際に、場合によって
Cannot read property 'xxx' of undefined.
が発生してしまう
- 目的のプロパティへのパスの途中で
undefined
になる場合に発生
解決方法
lodash
の get メソッドを利用する
- パスの途中で
undefined
になる場合は、undefined
もしくは 指定した値
を返してくれる
Document
使い方
_.get(object, path, [defaultValue])
_.get(対象のオブジェクト, プロパティのパス, [undefinedの場合に返す値(省略した場合は undefined を返す)])
例
import _ from "lodash";
const user1 = {
id: 1,
email: 'john.smith@example.com',
profile: {
name: 'John Smith',
},
};
const user2 = {
id: 2,
email: 'taro.yamada@example.com',
profile: undefined,
};
console.log(user1.profile.name); //John Smith
console.log(user2.profile.name); //TypeError: Cannot read property 'name' of undefined
// lodash の get メソッドを利用
console.log(_.get(user2, 'profile.name')); //undefined
console.log(_.get(user2, 'profile.name', 'no name')); //no name