In Javascript. how can I tell if a field exists inside an object?

前端 未结 5 718
余生分开走
余生分开走 2021-01-31 07:12

And of course I want to do this code-wise. It\'s not that there isn\'t alternative to this problem I\'m facing, just curious.

相关标签:
5条回答
  • 2021-01-31 07:29

    In addition to the above, you can use following way:

    if(obj.myProperty !== undefined) {
    }
    
    0 讨论(0)
  • 2021-01-31 07:32

    UPDATE: use the hasOwnProperty method as Gary Chambers suggests. The solution below will work, but it's considered best practice to use hasOwnProperty.

    if ('field' in obj) {
    }
    
    0 讨论(0)
  • 2021-01-31 07:38

    This will ignore attributes passed down through the prototype chain.

    if(obj.hasOwnProperty('field'))
    {
        // Do something
    }
    
    0 讨论(0)
  • 2021-01-31 07:42

    After much frustration trying to test a field name which is passed via a variable, I came up with this:

    `function isset(fName){ 
        try{
            document.getElementById(fName).value=document.getElementById(fName).value;  
            return true;
        }catch(err){
            return false;
        }
     }
    

    `

    The function uses the try/catch function of javascript - if it can't set the field value it will trigger an error which is caught and passed back as false, otherwise true is returned.

    0 讨论(0)
  • 2021-01-31 07:45

    There is has method in lodash library for this. It can even check for nested fields.

    _.has(object, 'a');     
    _.has(object, 'a.b');
    
    0 讨论(0)
提交回复
热议问题