0

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: ""}]

4 Answers 4

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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

Comments

0

Solution using Object.values

const arr1 = [{capacity: ""}, {color: ""}];
const arr2 = [{capacity: "full"}, {color: "blue"}];
const arr3 = [{capacity: ""}, {color: "blue"}];

function arePropertiesEmpty( arr){

    for( let i = 0 ; i < arr.length ; i++){
        // values is not empty
        if( Object.values(arr[i])[0].length ) {
            return false;
        }
    }
    return true;
}

// another solution
function arePropertiesEmpty2( arr){

    let filterArr =  arr.filter(eliminateEmptyElementsFromArray);  

    function eliminateEmptyElementsFromArray( el ){
        return Object.values(el)[0].length > 0
    }

    return filterdArr.length > 0 ? false : true;
}

console.log(arePropertiesEmpty(arr1));//true
console.log(arePropertiesEmpty(arr2));//false
console.log(arePropertiesEmpty(arr3));//false

console.log(arePropertiesEmpty2(arr1));//true
console.log(arePropertiesEmpty2(arr2));//false
console.log(arePropertiesEmpty2(arr3));//false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.