如何用原生JavaScript替代Lodash链式调用以提升性能与可读性?
Great question! Let’s break this down from both native JavaScript and improved Lodash usage angles to give you a clear answer.
First: Native JavaScript Replacement
Your original Lodash chain handles three key tasks:
- Extract the
nameproperty from every item inuserCollection - Remove falsy values (like
null,undefined, empty strings,0, etc.) - Deduplicate the remaining values
You can replicate this entirely with ES6+ native features, no Lodash required:
[...new Set(userCollection.map(user => user.name).filter(Boolean))]
Here’s the breakdown of each part:
userCollection.map(user => user.name): Explicitly maps each user to theirnameproperty, replacing Lodash’s shorthandmap('name').filter(Boolean): Removes all falsy values—this works becauseBoolean()converts values to their boolean equivalent, andfilterkeeps only truthy results (matches Lodash’scompact()behavior)[...new Set(...)]): Converts the filtered array to a Set (which automatically deduplicates unique values) and spreads it back into an array, replacing Lodash’suniq()
Note: ES6 Sets preserve insertion order, so this maintains the same sequence as your original Lodash chain.
Second: Evaluating Your Nested Lodash Approach
Your attempt _.uniq(_.compact(userCollection.map('name'))) is absolutely an improvement over using chain()—and it has tangible value:
- Better performance: Lodash’s
chain()creates a wrapped object that tracks method calls, only executing the full pipeline when you callvalue(). Nested direct calls avoid this wrapper overhead, running each step immediately with minimal extra processing. - Clearer readability: The nested structure makes data flow explicit (map → compact → uniq) without the extra boilerplate of
chain()andvalue(). It’s easier to scan and understand at a glance. - Less error-prone: You don’t have to remember to end the chain with
value()—a common gotcha with Lodash chains that can lead to unexpected results if forgotten.
Final Thoughts
If you want to reduce dependencies, the native JS solution is perfect—it’s lightweight and doesn’t require Lodash at all. If you still prefer using Lodash (for consistency with other code or edge cases like handling non-primitive values in uniq()), your nested approach is far better than relying on chain().
内容的提问来源于stack exchange,提问作者kyserslick

