Reputation: 1
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: ""}]
Upvotes: 0
Views: 1313
Reputation: 15
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
Upvotes: 0
Reputation: 7616
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
Upvotes: 0
Reputation: 344
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);
Upvotes: 0
Reputation: 64657
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)
Upvotes: 2