Checking if a key exists in a JavaScript object?

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

    If you want to check for any key at any depth on an object and account for falsey values consider this line for a utility function:

    var keyExistsOn = (o, k) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;
    

    Results

    var obj = {
        test: "",
        locals: {
            test: "",
            test2: false,
            test3: NaN,
            test4: 0,
            test5: undefined,
            auth: {
                user: "hw"
            }
        }
    }
    
    keyExistsOn(obj, "")
    > false
    keyExistsOn(obj, "locals.test")
    > true
    keyExistsOn(obj, "locals.test2")
    > true
    keyExistsOn(obj, "locals.test3")
    > true
    keyExistsOn(obj, "locals.test4")
    > true
    keyExistsOn(obj, "locals.test5")
    > true
    keyExistsOn(obj, "sdsdf")
    false
    keyExistsOn(obj, "sdsdf.rtsd")
    false
    keyExistsOn(obj, "sdsdf.234d")
    false
    keyExistsOn(obj, "2134.sdsdf.234d")
    false
    keyExistsOn(obj, "locals")
    true
    keyExistsOn(obj, "locals.")
    false
    keyExistsOn(obj, "locals.auth")
    true
    keyExistsOn(obj, "locals.autht")
    false
    keyExistsOn(obj, "locals.auth.")
    false
    keyExistsOn(obj, "locals.auth.user")
    true
    keyExistsOn(obj, "locals.auth.userr")
    false
    keyExistsOn(obj, "locals.auth.user.")
    false
    keyExistsOn(obj, "locals.auth.user")
    true
    

    Also see this NPM package: https://www.npmjs.com/package/has-deep-value

提交回复
热议问题