简体   繁体   中英

Check if an object exists within an array

I have the following array, myArray and object, myObject . Is there a way I can determine if myObject exists within 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.

 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

 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. This returns "-1" if if the desired element is not found: You can also use the "includes" method of the array like this:

 var nums=[1, 2] console.log(nums.includes(1));//returns true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM