I'm trying to understand how to get from an array of objects 2 specific keys and compare them with 2 other values for a boolean statement.
What I need to achieve is that for all results from an array of objects I have to check if
ownerId or ownerType are equal to example this.ownerId or this.ownerType.
To give an example I have a result Obj as
const results = [
{
ownerId: '1'
ownerType: SOME_TYPE,
id: 1
...
<other key_values>
...
},
{
ownerId: '1'
ownerType: SOME_TYPE,
id: 2
...
<other key_values>
...
},
... more ...
];
From the results, I have to extract all ownerId and ownerType and check if all are equal to another value as example
(ownerType === 'USER' && ownerId === userId) ||
(ownerType === 'PARTICIPANT' && ownerId === participantId)
So that means where all ownerType === 'USER' && all ownerId === to this userId then is true.
like all ownerId in my examples are 1 and we suppose 'USER' as a type then that is true.
but
If the result doesn't have all the same ownerId that is false.
I'm not sure what kind of function I need to write for it.
If any comments I'll try to explain better m issue
Just loop through all the items and check them 1 by 1, when you find an item that doesn't pass, set the resultBoolean to false & stop the loop. When it goes through all the items witheout setting the boolean to false, everything passed.
let resultBoolean = true;
const userId = '5';
for (let i = 0; i < results.length; i++) { //loop through all the array items
if (results[i].ownerId !== userId || results[i].ownerType !== "USER") { //check if this item doesn't have the specified requirements
resultBoolean = false; //if it doesn't you know that not all items have the correct ownerId & ownerType
break; //no need to continue looking because we already know its false
}
}
If I understand correctly, you might want to go with the filter method here
const concernedUsers = results.filter((user) => {
// Fail if there's no ownerType or userId
if (!user.ownerType || !user.userId) return false;
// Check for USER/PARTICIPANT type and userId/ownerId
return
['USER', 'PARTICIPANT'].indexOf(user.ownerType) > -1 &&
ownerID === user.userId;
});
concernedUsers.map((user) => { /*do something*/ });