Home > Software design >  How to compare object key as array value and assign a value to the variable?
How to compare object key as array value and assign a value to the variable?

Time:09-28

I have an object that contains multiple ids in an array:

"Headers" [
  {
    ...
    "listOfIds": [236, 242, 250, 289],
    ...
  }
]

In my react component how can I use this array to compare if the ids in my redux store matches with any of the ones in the array. If it contains any of those ids, then I need to apply the class name to the variable.

My current code:

const reduxState = useSelector(state=> state);

_.map(Headers, (item, index) => {
  const { listOfIds } = item;
  let className = '';
  if(_.get(reduxState, 'common.id', null) != listOfIds) {
    className = 'hidden'
  }
})

CodePudding user response:

i dont use react but maybe you could use the "includes()" function of array types.

For example:

let array = [236, 242, 250, 289];
let find = 250;
if (array.includes(find)) { 
// your code
}

CodePudding user response:

You can use Array.some:

const hasCommonId = Headers.some(({listOfIds}) => listOfIds.includes(reduxState?.common.id));

let className;
if (hasCommonId) {
  className = 'hidden'; // this should probably be a call to setState
}
  • Related