1

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

2 Answers 2

1

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

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

1 Comment

Thx, this answer is more suitable for me
1

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)

Comments

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.