Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Search for an object in an array using filtering object as a parameter

What's the most efficient way to search for object in an array using another object (not a function).

In javascript there is an array method .find() that accepts a callback to seek an item. How to create a similar function that accepts an object representing an object I want to find (that satisfies provided key-value conditions)? For example:

const array = [
   {
       param1: 'abc',
       param2: 'def',
       param3: 123,
   },
   {
       param1: 'test',
       param2: 'test2',
       param3: 321,
   },
   {
       param1: 'zzz',
       param2: 'test2',
       param3: 333,
   }
]

findInArray(array, {
   param1: 'test',
   param2: 'test2'
}) // must return 2nd object in an array
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try this code, you can define your filter and loop on the array to find your desired item .

var filter = {
   param1: 'test',
   param2: 'test2'
};
const array = [
   {
       param1: 'abc',
       param2: 'def',
       param3: 123,
   },
   {
       param1: 'test',
       param2: 'test2',
       param3: 321,
   },
   {
       param1: 'zzz',
       param2: 'test2',
       param3: 333,
   }
]

item = array.filter(function(item) {
  for (var key in filter) {
    if (item[key] === undefined || item[key] != filter[key])
      return false;
  }
  return true;
});

console.log(item)

about 4 years ago · Juan Pablo Isaza Report

0

You can combine Array.find() with a loop that iterates over your query object's keys:

const array = [{
    param1: 'abc',
    param2: 'def',
    param3: 123,
  },
  {
    param1: 'test',
    param2: 'test2',
    param3: 321,
  },
  {
    param1: 'zzz',
    param2: 'test2',
    param3: 333,
  }
]
, findInArray = (arr, query) => 
  arr.find(el => {
    let result = true
    for(const key in query){
      if(el[key] !== query[key]){
        result = false
        break
      }
    }
    return result
  })

console.log(findInArray(array, {
  param1: 'test',
  param2: 'test2'
}))

console.log(findInArray(array, {
  param1: 'abc',
  param3: 123
}))

console.log(findInArray(array, {
  param1: 'abc',
  param2: 'abc',
  param3: 123
}))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!