Checking if a key exists in a JavaScript object?

前端 未结 22 2242
礼貌的吻别
礼貌的吻别 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:45

    New awesome solution with JavaScript Destructuring:

    let obj = {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
    };
    
    let {key1, key2, key3, key4} = obj;
    
    // key1 = "value1"
    // key2 = "value2"
    // key3 = "value3"
    // key4 = undefined
    
    // Can easily use `if` here on key4
    if(!key4) { console.log("key not present"); } // Key not present
    

    Do check other use of JavaScript Destructuring

提交回复
热议问题