Home > Enterprise >  check if every object property in object array is not empty string
check if every object property in object array is not empty string

Time:10-19

I have an array of objects, every object has a property and their initial value is empty string. how can I check if every property value of these objects is not empty string and if it is not empty I want to return true. this is how the array of objects look like (in this example It should return false):

const arr = [{capacity: ""}, {color: ""}]

CodePudding user response:

You could use .some, .every and Object.values:

const arr = [{capacity: ""}, {color: ""}]
const someAreNotEmpty = arr.some((el) => Object.values(el).every(e => e !== ''));

console.log(someAreNotEmpty)

const arr2 = [{capacity: "2"}, {color: ""}]
const someAreNotEmpty2 = arr2.some((el) => Object.values(el).every(e => e !== ''));

console.log(someAreNotEmpty2)

CodePudding user response:

You can iterate through each object using forEach and, then use for..in to access each property and check if its value is an empty string.

const arr = [{capacity: ""}, {color: ""}, {size: "12"}];
const newArr = []

arr.forEach(i => {
  for (const property in i) {
    if (i[property] === '') newArr.push(false);
    else {
      newArr.push(true);
    } 
  }
});

console.log(newArr);

CodePudding user response:

You can walk through the array and check for the property value:

const arr = [{capacity: ""}, {color: ""}, {yes: "indeed"}];
let allSet = true;
arr.forEach(o => {
  let keys = Object.keys(o);
  if(keys.length && !o[keys]) {
    allSet = false;
  }
});
console.log('arr: '   JSON.stringify(arr));
console.log('allSet: '   allSet);

Output:

arr: [{"capacity":""},{"color":""},{"yes":"indeed"}]
allSet: false
  • Related