Home > Enterprise >  using includes in React with arrays
using includes in React with arrays

Time:07-07

I've done a few apollo queries in react and I'm trying to run an includes check against them. It however it always comes up false in the console log. Here's my code:

const onSubmit = (data: any) => {
console.log (data1)
console.log(data2)
console.log(data2.item)
console.log([data1].includes(data2.item))}

and here's the output:

console.log(data1): Test Array(2)
0: {Name: 'TEST', item: 'Crayons'}
1: {Name: 'TEST', item: 'Taco'} 
console.log(data2) : {Name: 'Jack', place: 'Home', item: 'Taco'}
console.log(data2.item) : Taco
console.log([data1].includes(data2.item)) : False

I'm looking for the output of that second column 'item' where taco matches to come up as true.

I've also tried accessing by data1.item[1].item but it still returned a false.

It may be because the type is an object?

Is there a simple way to check the entire second column of data1? (item). The list only gets bigger

CodePudding user response:

Include will check to see if the objects are the same by reference value. You can check if an entry's item is matching by using some.

console.log(data1.some(d => d.item === data2.item));
  • Related