[英]Is there a function which returns true or false when searching for an object in an array of objects?
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.我通过浏览 stackoverflow 找到的答案,例如在使用jQuery.grep 的 JavaScript 对象数组中按 id 查找对象或在 Javascript 中的对象数组中查找值返回找到的对象。 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:但我的意思是,如果有一种方法可以使用这样的 JS 方法:
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. filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
If there is no native JavaScript method (returning true or false) how can update the isObjectExist()
function to return true or false?如果没有原生 JavaScript 方法(返回 true 或 false),如何更新isObjectExist()
函数以返回 true 或 false?
The Array.prototype.some
method: Array.prototype.some
方法:
The some() method checks if any of the elements in an array pass a test (provided as a function). some() 方法检查数组中的任何元素是否通过测试(作为函数提供)。 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) some() 方法对数组中存在的每个元素执行一次函数:如果找到函数返回真值的数组元素, some() 返回真(并且不检查剩余值)
I'm sharing an example based on comments above, it may help others:我正在根据上面的评论分享一个例子,它可能会帮助其他人:
const listOfObjecs = [ { id: 1, name: "Name 1", score: 11 }, { id: 3, name: "Name 3", score: 33 }, { 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 }, { id: 3, name: "Name 3", score: 33 }, ]; const search1 = { id: 3, name: "Name 3", score: 33 }; const search2 = { id: 9, name: "Name 3", score: 33 }; // Using Array.prototype.some() const resSomeSearch1 = listOfObjecs.some(item => JSON.stringify(item) === JSON.stringify(search1)); console.log(`resSome(search1): ${resSomeSearch1}`); // outputs: true const resSomeSearch2 = listOfObjecs.some(item => JSON.stringify(item) === JSON.stringify(search2)); console.log(`resSome(search2): ${resSomeSearch2}`); // outputs: false // Using Array.prototype.filter() const resFilterSearch1 = !!listOfObjecs.filter(item => JSON.stringify(item) === JSON.stringify(search1)).length; console.log(`resFilter(search1): ${resFilterSearch1}`); // outputs: true const resFilterSearch2 = !!listOfObjecs.filter(item => JSON.stringify(item) === JSON.stringify(search2)).length; console.log(`resFilter(search2): ${resFilterSearch2}`); // outputs: false // Using Array.prototype.find() const resFindSearch1 = !!listOfObjecs.find(item => JSON.stringify(item) === JSON.stringify(search1)); console.log(`resFind(search1): ${resFindSearch1}`); // outputs: true const resFindSearch2 = !!listOfObjecs.find(item => JSON.stringify(item) === JSON.stringify(search2)); console.log(`resFind(search2): ${resFindSearch2}`); // outputs: false
This works for me:这对我有用:
const findInArray = (myArray, item) => {
!!myArray.find((el) => el == item)
};
Update, even easier:更新,更简单:
['cat', 'dog', 'bat'].includes('dog');
The find() method returns a value of the first element in the array that satisfies the provided testing function. find() 方法返回数组中满足提供的测试函数的第一个元素的值。 Otherwise undefined is returned.否则返回 undefined。 So no boolean result.所以没有布尔结果。
@AlaDejbali's comment on his post. @AlaDejbali 对他的帖子的评论。
Let's take this array :让我们以这个数组为例:
var arr = [{
name: "Ala",
age: 20,
},
{
name: "Jhon",
age: 22,
},
{
name: "Melissa",
age: 12,
},
];
Of course, find()
returns the whole object inside your array but that depends on your implemented function inside find for example :当然, find()
返回数组中的整个对象,但这取决于您在 find 中实现的函数,例如:
function findObject(arr, value) {
if (Array.isArray(arr)) {
return arr.find((value) => {
return value.age === 20;
});
}
}
When we call this function like this :当我们像这样调用这个函数时:
console.log(findObject(arr, 20));
The resul will be :结果将是:
{name: "Ala", age: 20}
And as far as we know undefined
is not an object
so we can test the returned result :据我们所知undefined
不是一个object
所以我们可以测试返回的结果:
function findObject(arr, value) {
const element = arr.find((value) => {
return value.age === 20;
});
return typeof element === "object" ? true : false;
}
Or in other way :或以其他方式:
function findObject(arr, value) {
const element = arr.find((value) => {
return value.age === 20;
});
return typeof element === "undefined" ? false : true;
}
return boolean value if an object exists in array of objects.如果对象存在于对象数组中,则返回布尔值。
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 object = { id: 3, name: "Name 3", score: 33 }; var booleanValue = listOfObjecs.filter((item) => item.id === object.id && item.name === object.name && item.score === object.score).length > 0 console.log({booleanValue})
尝试这个:
!!arr.find(function(){...})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.