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

后端 未结 15 1681
走了就别回头了
走了就别回头了 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条回答
  • This works with me perfectly:

    checkProperties(obj) {
      let arr = [];
      for (let key in obj) {
        arr.push(obj[key] !== undefined && obj[key] !== null && obj[key] !== "");
      }
      return arr.includes(false);
    }
    

    This will return true or false if there is at-least one value is empty or something like that.

    0 讨论(0)
  • 2020-12-08 05:02
    let obj = { x: null, y: "hello", z: 1 };
    let obj1 = { x: null, y: "", z: 0 };
    
    !Object.values(obj).some(v => v);
    // false
    
    !Object.values(obj1).some(v => v);
    // true
    
    0 讨论(0)
  • 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/

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