简体   繁体   中英

How to compare object key as array value and assign a value to the variable?

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'
  }
})

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM