Home > Software design >  Getting odd results from a for loop inside a filter function
Getting odd results from a for loop inside a filter function

Time:04-07

I'm looping inside a filter. I want to get the values from vals array as my keys for my filter. When I loop through my vals array I keep getting returned the name and not both.

Ideally I would like the

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

CodePudding user response:

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)

CodePudding user response:

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'))
  • Related