[英]Check if an object exists within an array
I have the following array, myArray
and object, myObject
.我有以下数组, myArray
和 object, myObject
。 Is there a way I can determine if myObject
exists within myArray
?有没有办法可以确定myObject
是否存在于myArray
中?
const myArray = [ { id: 1, lastName: "Garland", firstName: "Darius", email: "test@example.com" },
{ id: 2, lastName: "Sexton", firstName: "Collin", email: "fake@example.com" } ]
const myObject = { lastName: "Sexton", email: "fake@example.com" }
You can make use of some
with every
to get the desired output.您可以使用some
来获得所需的every
。
const myArray = [ { id: 1, lastName: "Garland", firstName: "Darius", email: "test@example.com" }, { id: 2, lastName: "Sexton", firstName: "Collin", email: "fake@example.com" } ]; const myObject = { lastName: "Sexton", email: "fake@example.com" }; const result = myArray.some(k=>Object.entries(myObject).every(([key,v])=>k[key]===v)); const result2 = myArray.some(k=>Object.entries(k).every(([key,v])=>myObject[key]===v)); console.log(result); console.log(result2);
same as gorak but done with explicit generics functions与gorak相同,但使用显式 generics 函数完成
const objPartsExistInArr = (obj,arr) => arr.some(o=>Object.entries(obj).every(([k,v])=>o[k]===v)) const fullObjExistInArr = (obj,arr) => arr.some(o=>Object.entries(o).every(([k,v])=>obj[k]===v)) const myArray = [ { id: 1, lastName: 'Garland', firstName: 'Darius', email: 'test@example.com' }, { id: 2, lastName: 'Sexton', firstName: 'Collin', email: 'fake@example.com' } ] const myObjP = { lastName: 'Sexton', email: 'fake@example.com' } const myObjF = { id: 2, lastName: 'Sexton', firstName: 'Collin', email: 'fake@example.com' } console.log('objPartsExistInArr ->', objPartsExistInArr( myObjP, myArray ) ) console.log('fullObjExistInArr ->', fullObjExistInArr( myObjF, myArray ) )
Use the "indexOf" method of the array.使用数组的“indexOf”方法。 This returns "-1" if if the desired element is not found: You can also use the "includes" method of the array like this:如果未找到所需元素,则返回“-1”:您还可以使用数组的“includes”方法,如下所示:
var nums=[1, 2] console.log(nums.includes(1));//returns true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.