Checking if a key exists in a JavaScript object?

前端 未结 22 2229
礼貌的吻别
礼貌的吻别 2020-11-21 22:57

How do I check if a particular key exists in a JavaScript object or array?

If a key doesn\'t exist, and I try to access it, will it return false? Or throw an error?<

22条回答
  •  忘了有多久
    2020-11-21 23:46

    For those which have lodash included in their project:
    There is a lodash _.get method which tries to get "deep" keys:

    Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

    var object = { 'a': [{ 'b': { 'c': 3 } }] };
    
    console.log(
      _.get(object, 'a[0].b.c'),           // => 3
      _.get(object, ['a', '0', 'b', 'c']), // => 3
      _.get(object, 'a.b.c'),              // => undefined 
      _.get(object, 'a.b.c', 'default')    // => 'default'
    )


    This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.

提交回复
热议问题