Is there a way to check if an object exists in an array while excluding one property? I don't know which properties will exist in the object so I can't compare properties manually.
Based on the code below, I would want to check if obj
exists in arr
excluding prop3
.
Example:
const obj = {
"prop1": "value1",
"prop2": "value2"
}
const arr = [{
"prop1": "value1",
"prop2": "value2",
"prop3": "value3"
},
{
"prop1": "value4",
"prop2": "value5",
"prop3": "value6"
}
]
arr.indexOf(obj) > -1; // returns false, need something like this that returns true
User Array.findIndex() method to find index:
const keys = Object.keys(obj);
arr.findIndex((o) => {
return keys.every(k => o[k] && o[k] === obj[k])
});
Use a combination of Array.findIndex
, Object.keys
& Array.every
like so:
const obj = { "prop1": "value1", "prop2": "value2" } const arr = [{ "prop1": "value1", "prop2": "value2", "prop3": "value3" }, { "prop1": "value4", "prop2": "value5", "prop3": "value6" } ] const index = arr.findIndex(item => { // For every item of array: // - Iterate over obj keys // - If every k/v pair of obj matches ak/v pair of item // then it's a match return Object.keys(obj).every(key => item[key] === obj[key]) }) console.log(index)
Although if you just want to know if it exists or not, you should use Array.some
instead of Array.findIndex
.
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.