javascript - check if object is empty

前端 未结 5 1025
感情败类
感情败类 2021-02-05 08:57

I am trying to create to javascript/jquery test to check if my object is empty and cannot figure it out.

Here is the object when it has something in it:

         


        
相关标签:
5条回答
  • 2021-02-05 09:14

    You were testing sellers which is not empty because it contains mergedSellerArray. You need to test sellers.mergedSellerArray

    let sellers = {
      "mergedSellerArray": {}
    };
    if (Object.keys(sellers.mergedSellerArray).length === 0 && sellers.mergedSellerArray.constructor === Object) {
      console.log("sellers is empty!");
    } else {
      console.log("sellers is not empty !");
    }

    0 讨论(0)
  • 2021-02-05 09:15

    If you are using lodash library, you have an elegant way to check an empty object, array, map or a set. I presume you are aware of ES6 Import statement.

    import {isEmpty} from "lodash"
    
    let obj = {};
    console.log(isEmpty(obj)); //Outputs true.
    
    let arr = [];
    console.log(isEmpty(arr)); //Outputs true.
    
    obj.name="javascript";
    console.log(isEmpty(obj)); //Outputs false.
    

    So, for your code,

    isEmpty(mergedSellerArray); //will return true if object is not empty.
    

    Hope this answer helped.

    0 讨论(0)
  • 2021-02-05 09:22

    Can create the helper function :

    const isEmpty = inputObject => {
      return Object.keys(inputObject).length === 0;
    };
    

    Can use it like:

    let inputObject = {};
    console.log(isEmpty(inputObject))  // true.
    

    and

    inputObject = {name: "xyz"}; 
    console.log(isEmpty(inputObject)) // false
    
    0 讨论(0)
  • 2021-02-05 09:29

    Alternatively, you can write the isEmpty function on the Object prototype.

    Object.prototype.isEmpty = function() {
        for(var key in this) {
            if(this.hasOwnProperty(key))
                return false;
        }
        return true;
    }
    

    Then you can easily check if the object is empty like so.

    var myObj = {
        myKey: "Some Value"
    }
    
    if(myObj.isEmpty()) {
        // Object is empty
    } else {
        // Object is NOT empty (would return false in this example)
    }
    

    Source solution: https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty

    0 讨论(0)
  • 2021-02-05 09:30

    Here is in jQuery:

    $(document).ready(function(){
    	var obj={"mergedSellerArray":{}};
    	alert("is empty: "+$.isEmptyObject(obj.mergedSellerArray));
    
            var obj2={"mergedSellerArray":{"key1114":"1120"}};
    	alert("is empty: "+$.isEmptyObject(obj2.mergedSellerArray));
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    jsfidle: https://jsfiddle.net/nyqgbp38/

    0 讨论(0)
提交回复
热议问题