return boolean based on object condition inside array of objects

314 Views Asked by At

I feel like this is quite a simple question but I've been struggling with it for the last few hours..

    data[0].fieldArray.fieldGroup[4].hideExpression = (model: any, formState: any) => {
      for (const item of formState.mainModel.config.linkItems) {
        console.log(item);
        if (item.displaySubmenu) {
          return false;
        } else {
          return true;
        }
      }
    };

My formState contains a Array with multiple objects inside, I need to determine if the value inside of each object (displaySubmenu) is either true of false and return true or false to trigger hideExpression .. So far I've only managed to either trigger all the elements on page or either the first or the last one..

I've also tried to used forEach, map but I feel like I'm missing something quite simple just can't understand what

1

There are 1 best solutions below

2
On

You could use the array.filter method for this:

data[0].fieldArray.fieldGroup[4].hideExpression = (model: any, formState: any) => {
  return formState.mainModel.config.linkItems.filter(linkItem => {
    return linkItem.displaySubmenu;
  }).length > 0;
};

The filter method returns an array with the items that matches the condition. If one of the items in linkItems has displaySubmenu as true it will be returned in the return array of the filter method. So when we get the length of that array it will be bigger than 0 which results in a true boolean.

When linkItems doesn't have an item with displaySubmenu the return filter will return an empty array because none of the items match the condition and the length will be 0 which results in a false boolean.

More info about the filter method: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter