Reputation: 623
I want to filter an object based on key or value using Object.fromEntries
and Object.entries
, but when I try to use logical OR || I can't do what I want. Is there a good solution without introducing another method or loop?
const object1 = { a: 1, b: 2, c: 3 };
const object4 = Object
.fromEntries(Object
.entries(object1)
.filter(([key, val])=>key!=="a"||val!== 2));
// logic goes wrong!
console.log(object4);
// { a: 1, b: 2, c: 3 } I want { c: 3 }, filter any key with "a" or value with 2
I want a proper boolean OR, if any of its arguments are true, it returns true, otherwise it returns false. I have read JS does something weird, but how to sort it?
Upvotes: 0
Views: 1569
Reputation: 11080
What you have is a proper boolean OR.
Array.prototype.filter
calls the function for each element of the array, and if the function returns true, it is included in the resultant array. This is probably where your confusion lies.
Let's simulate your condition on each entry:
"a" !== "a" || 1 !== 2
-> false || true
-> true
, item is included"b" !== "a" || 2 !== 2
-> true || false
-> true
, item is included"c" !== "a" || 3 !== 2
-> true || true
-> true
, item is includedAs you can see, the boolean OR is working exactly as you've described. You're getting the correct behavior already.
If you want to exclude a
and b
, you're likely looking for boolean AND &&
, as you want all conditions to be true for the item to be a candidate for inclusion in the result array.
See here for demonstration:
const object1 = { a: 1, b: 2, c: 3 };
const object4 = Object.fromEntries(
Object.entries(object1).filter(
([key, val])=>key!=="a"&&val!== 2
)
);
console.log(object4);
Upvotes: 3
Reputation: 241808
To get the operation you're looking for, you need the logical AND operator, not OR.
key !== "a" && val !== 2
Alternatively, you could express it with OR, by negating the entirety of the expression, using positive comparisons instead of negative ones.
!(key === "a" || val === 2)
Upvotes: 5