I'm looking for a good way to check if an object exist in an array of objects. The intended result is true when all keys/values are present in the same object in that array.
The answers I found by browsing stackoverflow like Find object by id in an array of JavaScript objects which is using jQuery.grep or Find a value in an array of objects in Javascript return the found object. What I'm looking for is a boolean result (not the found object).
I know that I can loop for all array elements and then compare each value....etc
But what I mean is if there is a way to use JS methods like this:
var listOfObjecs = [
{id: 1, name: "Name 1", score: 11},
{id: 2, name: "Name 2", score: 22},
{id: 3, name: "Name 3", score: 33},
{id: 4, name: "Name 4", score: 44},
{id: 5, name: "Name 5", score: 55},
];
var isObjectExist = function(search){
return listOfObjecs.filter(function(obj){
if(obj.id===search.id && obj.name===search.name && obj.score===search.score){
return true;
}
return false;
});
}
console.log( isObjectExist({id: 3, name: "Name 3", score: 33}) );
//outputs the found object [{id: 3, name: "Name 3", score: 33}]
console.log( isObjectExist({id: 9, name: "Name 3", score: 33}) );
//outputs an empty object []
This is because:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
If there is no native JavaScript method (returning true or false) how can update the isObjectExist()
function to return true or false?
The Array.prototype.some
method:
The some() method checks if any of the elements in an array pass a test (provided as a function). The some() method executes the function once for each element present in the array: If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining values)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments