1

I've got a list:

const list = [{
  name: 'Simon',
  age: 18
}, {
  name: 'Simon',
  age: 22
}, {
  name: 'Martha',
  age: 18
}]

and my filter params are:

const filterParams = {
  name: 'Simon',
  age: 18
}

I want to apply my filter params to filter my list, but I can pass one or 2 params.

 {
  name: 'Simon'
}

 OR

 {
  name: 'Simon',
  age: 18
}

My ideia is to iterate through my filterParams and filter those entries in the list.

const filteredList = Object.entries(filterParams).map(([key, value]) => list.filter(l => l[key] === value))

USE CASES

  1. If I pass
{
  name: 'Simon',
  age: 18
}

the expected result is:

const expectedResult = [{
  name: 'Simon',
  age: 18
}]
  1. If I pass
{
  name: 'Simon',
}

the expected result is:

const expectedResult = [{
  name: 'Simon',
  age: 18
}, {
  name: 'Simon',
  age: 22
}]

Somehow I couldn't figure out yet and obviously my filter function is not working. Here's a code snippet.

const filterParams = {
  name: 'Simon',
  age: 18
}

const list = [{
  name: 'Simon',
  age: 18
}, {
  name: 'Simon',
  age: 22
}, {
  name: 'Martha',
  age: 18
}]



const filteredList = Object.entries(filterParams).map(([key, value]) => list.filter(l => l[key] === value))


const expectedResult = [{
  name: 'Simon',
  age: 18
}]

console.log('filteredList', filteredList)

Thanks in advance

1
  • const filteredList = list.filter(l => Object.keys(filterParams).every(key => l[key] === filterParams[key])). Commented Jan 23, 2023 at 12:04

1 Answer 1

2

You're going thru the filters, and mapping them to each list item. What you need to do is map the list items instead, and compare each item's values to the filters.

const filterParams = {
  name: 'Simon',
  age: 18
}

const list = [{
  name: 'Simon',
  age: 18
}, {
  name: 'Simon',
  age: 22
}, {
  name: 'Martha',
  age: 18
}]

const filteredList = list.filter(item => {
  return Object.keys(filterParams).every(param => {
    return filterParams[param] === item[param];
  });
});

const expectedResult = [{
  name: 'Simon',
  age: 18
}]

console.log('filteredList', filteredList)

Sign up to request clarification or add additional context in comments.

1 Comment

x => { return y } can be simply x => y

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.