0

I want to check if all certain properties of an object are set to a specific value. But how can I achieve this in a good way?

the output (data.items) looks like this:

0: {id_menu: 1234, menunummer: "1", menu_naam: "test1", permission: "Y"}
1: {id_menu: 1235, menunummer: "2", menu_naam: "test2", permission: "Y"}
2: {id_menu: 1236, menunummer: "2", menu_naam: "test3", permission: "Y"}

but how can I check if permission property of all data.items are set to "Y"

I tried this:

 for(var i = 0; i < data.items.length; i++){
    console.log('permissionMENU',data.items[i].permission);
    if(data.items[i].permissie === "N"){
       console.log('WORKS');
   }
}

But this check every item seperatly how can I check if all items their permission are set to "Y"

Sireini
  • 4,142
  • 12
  • 52
  • 91

4 Answers4

4

You can use every:

data.items.every(item => item.permission === 'Y')
thedude
  • 9,388
  • 1
  • 29
  • 30
1

Since data.items is an array, you can try to use Array.prototype.filter method:

data.items.filter(x => x.permission === 'Y').length === data.items.length
Tân
  • 1
  • 15
  • 56
  • 102
-1

let dataItems = Object.values(data.items);
dataItems.filter(dataItem => dataItem.permission === 'Y').length === dataItems.length;

The Object.values function will give you an array with just the objects. after that we filter through them just returning the items when the permission is Y and we compare that length with the actual length.

(Haven't actually tested this code but this should work)

Gijs Beijer
  • 560
  • 5
  • 19
-1

from your array you can use array.filter, which will give a new array of objects which satisfies the condition.

use a if else condition to check whether the filteredarray has any elements if filteredarray.length ===0 there is no objects which means every object property permission has Y.

if the length is !=0 (not equal to zero), some objects property permission has some another value which means N. So you can print out the elements.

See the below code. I hope this will solve your issue.

Note: i have added one more object which has the property of permission has N in order to show the else case how it works. You can remove the object.

let arr = [{id_menu: 1234, menunummer: "1", menu_naam: "test1", permission: "Y"},
{id_menu: 1235, menunummer: "2", menu_naam: "test2", permission: "Y"},
{id_menu: 1236, menunummer: "2", menu_naam: "test3", permission: "Y"},
{id_menu: 1236, menunummer: "2", menu_naam: "test3", permission: "N"}
]

let filteredArr = arr.filter(o => o.permission != "Y")

if(filteredArr.length === 0){
console.log("All properties has permission as Yes(Y)")
}else{
console.log("Some properties have permission has No(N) which are", filteredArr)
}
Learner
  • 8,379
  • 7
  • 44
  • 82