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

前端 未结 16 2532
野性不改
野性不改 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

    If you are using lodash, you could use their "has" function. It is similar to the native "in", but allows paths.

    var testObject = {a: {b: {c: 'walrus'}}};
    if(_.has(testObject, 'a.b.c')) {
      //Safely access your walrus here
    }
    

提交回复
热议问题