'Why do we needed pickBy in Lodash when We can use delete operator instead?
I have a small question.
Why do we needed pickBy in Lodash or similar? Just simple with delete operator.
// Input
const source = {
user: {
firstname: "John",
lastname: "Done"
},
password: "123"
};
// Output
const result = {
user: {
firstname: "John",
lastname: "Done"
}
};
There are many ways to get the desired result: https://codesandbox.io/s/cool-rubin-xlj25k?file=/src/index.ts
With pickBy:
const result = _.pickBy(
source,
(value, key) => !(key === "password" && value === "123")
);
With native:
const result = Object.fromEntries(
Object.entries(source).filter(
([key, value]) => !(key === "password" && value === "123")
)
);
And with delete operator: Lightweight, fastest, no loop,...vv
const result = Object.assign({}, source);
if (result.password === "123") {
delete result.password;
}
So, I'm looking for reasons not to use delete operator.
--UPDATED for mutation issue:
All ways are mutated user.firstname
source.user.firstname = "New first name";
console.log({ source, result });
{
"source": {
"user": {
"firstname": "New first name",
"lastname": "Done"
},
"password": "123"
},
"result": {
"user": {
"firstname": "New first name",
"lastname": "Done"
}
}
}
Solution 1:[1]
Lightweight, fastest, no loop,...vv
Sure, if you're deleting a single key, use delete.
pickBy, as the name implies, is meant for predicate-function-based picking (filtering) of items, which is not what delete does without a loop.
For instance, if your (fictitious) goal is to turn
{
"foo": "bar",
"baz": "quux",
"beq": "berp",
"uub": "uuzpq",
}
into
{
"beq": "berp",
"uub": "uuzpq",
}
i.e. where the key and value start with the same letter – who knows why you'd need that but that's beside the point, you'd have a worse time with a loop and delete than with pickBy.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AKX |
