Benk I
Benk I

Reputation: 199

How to check if array of object's properties are empty or not in javascript

I want to check the following array have any empty value or not

Example

The following should return true

[
    {
        "price": "12",
        "number": "1"
    },
    {
        "price": "12",
        "number": "1"
    }
]

The following should return false

[
    {
        "price": "12",
        "number": "1"
    },
    {
        "price": "12",
        "number": ""
    }
]

Upvotes: 0

Views: 122

Answers (2)

Peter Seliger
Peter Seliger

Reputation: 13376

function isNonEmptyValue(value) {
  return (
    (value != null)
    && (value !== '') 
  //&& any other *empty* value constraint
  );
}
function hasEntriesAndNoEmptyValues(item) {
  const values = Object.values(item);
  return (
    values.length >= 1 &&
    values.every(value => isNonEmptyValue(value))
  );
}

console.log(
  [{
    "price": "12",
    "number": "1",
  }, {
    "price": "12",
    "number": "",

  }].every(hasEntriesAndNoEmptyValues)
);
console.log(
  [{
    "price": "12",
    "number": "1",
  }, {
    "price": "12",
    "number": " ",

  }].every(hasEntriesAndNoEmptyValues)
);
console.log(
  [{

  }, {
    "price": "12",
    "number": " ",

  }].every(hasEntriesAndNoEmptyValues)
);

Upvotes: 1

Spectric
Spectric

Reputation: 31992

You can use Array.some and Object.values to check whether one of the property value's length of an item in the array is smaller than 1:

const arr=[{price:"12",number:"1"},{price:"12",number:"1"}];

const isValid = !arr.some(e => Object.values(e).some(f => f.length < 1))

console.log(isValid)

Upvotes: 1

Related Questions