ronoc4
ronoc4

Reputation: 637

Getting odd results from a for loop inside a filter function

I'm looping inside a filter. I want to get the values from my vals array plus the keys(name, description) for my filter.

When I iterate through my vals array, I keep getting returned the name but not the key.

Ideally I would like the return method to give me key and value.

return x[this.searchValues[i]].includes('phil')

to be return x.name.includes('phil') return x.decription.includes('phil')

  const vals = ['name', 'decription']

  const arr =[{
    name: 'joe',
    decription: 'is a guy who likes beer'
   },
   name: 'phil',
    decription: 'is a super hero'
   }]

  this.result = arr.filter((x) => {
    for(let i = 0; i< vals.length; i++){
       return x[this.searchValues[i]].includes('phil');
    }
  })

Upvotes: 0

Views: 35

Answers (2)

Alan Omar
Alan Omar

Reputation: 4227

const vals = ['name', 'decription']

const arr =[{
  name: 'joe',
  decription: 'is a guy who likes beer'
 },{
 name: 'phil',
  decription: 'is a super hero'
 }]

 let result = arr.filter(e => vals.some(n => e[n].includes('phil')))
 
 console.log(result)

Upvotes: 1

kamil-now
kamil-now

Reputation: 79

Not sure what you're trying to achieve, you need to clearly state what is your goal in the question.

But if the goal is to get an object with name 'phil' from arr, then this could be done like this:

this.result = arr.filter(x => x.name === 'phil')

if you need to get objects where any property equals 'phil' then:

this.result = arr.filter(x => Object.keys(x).every(k => k === 'phil'))

Upvotes: 0

Related Questions