When you do the following
const isFavourited =
(Object.keys(obj).some(id => val == id &&
Object.values(obj).some(value => value == true))
);
You are not checking if the value of a particular index is true or false. Here is what actually happens when you have val = 1:
- the first
.some will iterate over all keys
val == id will be true for the second key which means:
- the
Object.values(obj).some(value => value == true) will be executed
- it returns
true because there is at least one value that is true in the entire obj. The result of this operation are not dependant on the value of the key - only whether it runs or not.
let obj = { 1:true, 2:false, 3:true }
let check = Object.values(obj).some(value => value == true)
console.log(check);
So, the algorithm checks if obj contains a given key and any value that is true, as opposed to if the value for a given key is true.
You do not need to loop over the object to verify this - fetching the value of obj[val] is all you need - if the key val doesn't exist, you'd get undefined back, otherwise you'll get the value. So you merely need to check if the value you got back is true or not:
let obj = { 1:true, 2:false, 3:true }
console.log(1, obj[1] == true);
console.log(2, obj[2] == true);
console.log(3, obj[3] == true);
console.log(42, obj[42] == true);
This can be further shortened to !!obj[index] using implicit casting to boolean.
true?obj[val]instead