Home > Net >  Filtering an array of objects by an object where all fields of the object values are respected
Filtering an array of objects by an object where all fields of the object values are respected

Time:01-01

I have an object like this:

let object = {
  name: "john",
  lastName: 'doe'
}

let arrayOfObjects = [
 {
  name: 'john',
  lastName: 'fake'
 },
 {
  name: 'josh',
  lastName: 'doe'
 },
 {
  name: 'john',
  lastName: 'doe',
 }
]

This is my code:

 let filteredNames = []
     arrayOfObjects.filter((map)=> {
      Object.keys(object).map(key=> {
        if(map[key].toLowerCase() === filters[key].toLowerCase()) {
          // console.log(map)
          filteredNames.push(map)
        }
      })
  })

Yet this returns all of them because at least one of the keys are respeted but not all of the keys How can I modify to fix this ? Thanks

CodePudding user response:

To achieve what you require you can use Object.values() to create an array of all the values you want to find in the object, and then Array.filter() and Array.every() to retrieve the object matching both of those values:

let filters = { name: "john", lastName: 'doe' }
let arrayOfObjects = [{ name: 'john', lastName: 'fake' }, { name: 'josh', lastName: 'doe' }, { name: 'john', lastName: 'doe' }]

let filterValues = Object.values(filters);
let filteredNames = arrayOfObjects.filter(obj => Object.values(obj).every(v => filterValues.includes(v)));

console.log(filteredNames);

CodePudding user response:

The combination of .filter() and .every() should do the trick for you:

let object = {
  name: "john",
  lastName: 'doe'
}

let arrayOfObjects = [
 {
  name: 'john',
  lastName: 'fake'
 },
 {
  name: 'josh',
  lastName: 'doe'
 },
 {
  name: 'john',
  lastName: 'doe',
 }
];

const res=arrayOfObjects.filter(o=>Object.entries(object).every(([k,v],i)=>v==o[k]));
console.log(res);

CodePudding user response:

I would get the entries first, because of having this entrie not build all time of iterating and then filter by looking at all entries.

const
    object = { name: "john", lastName: 'doe' },
    arrayOfObjects = [{ name: 'john', lastName: 'fake' }, { name: 'josh', lastName: 'doe' }, { name: 'john', lastName: 'doe' }],
    entries = Object.entries(object),
    result = arrayOfObjects.filter(o => entries.every(([k, v]) => o[k] === v));

console.log(result);

  • Related