skip to Main Content

I have an object

const load={trolleyNo:"",trolleyItems:[],cartType:""}

I need to check there are no empty values in this object. The array in the object should not be empty, and neither should the strings. How can I do this?

3

Answers


  1. This Function returns true if any value in the object is empty:

    hasEmptyKeys=function(obj){
    for (i in obj){
    if (obj[i].length==0){return true}}
    return false;
    }
    
    Login or Signup to reply.
  2. I’d go over the values and use every to check the value’s length:

    const bad = {trolleyNo: "", trolleyItems: [], cartType: ""}
    const good = {trolleyNo: "123", trolleyItems: ["cat", "hat"], cartType: "awesome"}
    
    function isPayloadValid(obj) {
      return Object.values(obj).every(v => v.length > 0);
    }
    
    console.log(`Is ${JSON.stringify(good)} valid? ${isPayloadValid(good)}`);
    console.log(`Is ${JSON.stringify(bad)} valid? ${isPayloadValid(bad)}`);
    Login or Signup to reply.
  3. you can write a function that iterates through the keys of your object and checks if they’re null and their length > 0:

    function isValidObject(obj) {
        for (let key in obj) {
            if (obj[key] == null || obj[key].length == 0) {
                return false;
            }
        }
        return true;
    }
    
    
    const load = {
      trolleyNo: null,
      trolleyItems: [],
      cartType: ""
    }
    
    console.log(isValidObject(load));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search