Determining if all attributes on a javascript object are null or an empty string

后端 未结 15 1801
走了就别回头了
走了就别回头了 2020-12-08 04:08

What is the most elegant way to determine if all attributes in a javascript object are either null or the empty string? It should work for an arbitrary number of attributes

15条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 05:02

    Based on adeneo's answer, I created a single line condition. Hope it will be helpful to someone.

    var test = {
      "email": "test@test.com",
      "phone": "1234567890",
      "name": "Test",
      "mobile": "9876543210",
      "address": {
          "street": "",
          "city": "",
          "state": "",
          "country": "",
          "postalcode": "r"
      },
      "website": "www.test.com"
    };
    
    if (Object.keys(test.address).every(function(x) { return test.address[x]===''||test.address[x]===null;}) === false) {
       console.log('has something');
    } else {
       console.log('nothing');
    }
    

    You can test it https://jsfiddle.net/4uyue8tk/2/

提交回复
热议问题