How to avoid 'cannot read property of undefined' errors?

前端 未结 16 2225
野性不改
野性不改 2020-11-22 06:02

In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:



        
16条回答
  •  别那么骄傲
    2020-11-22 06:20

    Lodash has a get method which allows for a default as an optional third parameter, as show below:

    const myObject = {
      has: 'some',
      missing: {
        vars: true
      }
    }
    const path = 'missing.const.value';
    const myValue = _.get(myObject, path, 'default');
    console.log(myValue) // prints out default, which is specified above

提交回复
热议问题