How to check if object has any properties in JavaScript?

后端 未结 16 2203
自闭症患者
自闭症患者 2020-12-04 08:10

Assuming I declare

var ad = {}; 

How can I check whether this object will contain any user-defined properties?

相关标签:
16条回答
  • 2020-12-04 09:03

    ES6 function

    /**
     * Returns true if an object is empty.
     * @param  {*} obj the object to test
     * @return {boolean} returns true if object is empty, otherwise returns false
     */
    const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0
    
    

    Examples:

    
    let obj = "this is an object with String constructor"
    console.log(pureObjectIsEmpty(obj)) // empty? true
    
    obj = {}
    console.log(pureObjectIsEmpty(obj)) // empty? true
    
    obj = []
    console.log(pureObjectIsEmpty(obj)) // empty? true
    
    obj = [{prop:"value"}]
    console.log(pureObjectIsEmpty(obj)) // empty? true
    
    obj = {prop:"value"}
    console.log(pureObjectIsEmpty(obj)) // empty? false
    
    
    0 讨论(0)
  • 2020-12-04 09:07

    Late answer, but some frameworks handle objects as enumerables. Therefore, bob.js can do it like this:

    var objToTest = {};
    var propertyCount = bob.collections.extend(objToTest).count();
    
    0 讨论(0)
  • 2020-12-04 09:08

    Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:

    var ad = {}; 
    Object.keys(ad).length;//this will be 0 in this case
    

    Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

    0 讨论(0)
  • 2020-12-04 09:08

    If you're using underscore.js then you can use the _.isEmpty function:

    var obj = {};
    var emptyObject = _.isEmpty(obj);
    
    0 讨论(0)
提交回复
热议问题