如何结合ES6箭头函数使用filter()筛选程序员职业对象?
Hey there! Let's break down what's going wrong with your current code and get it working correctly.
The Issue with Your Current Code
Your jobs array is filled with objects, not strings. When you write person === "programmer", you're trying to compare an object (like {receptionist: "James"}) directly to a string — which will always return false. That's why your solution array ends up empty!
Fixed Solutions
Since each object in your array has a single job as its key, here are a few straightforward ways to filter for the programmer:
- Check if the object has the "programmer" key using
in
var jobs = [{receptionist: "James"}, {programmer: "Steve"}, {designer: "Alicia"}]; var solution = jobs.filter(person => "programmer" in person);
This checks if the person object contains the programmer property (including properties inherited from the prototype chain).
- Use
Object.hasOwn()(recommended overinfor strict property checks)
var solution = jobs.filter(person => Object.hasOwn(person, "programmer"));
Object.hasOwn() only checks properties directly on the object itself, avoiding any prototype chain surprises.
- Check via object keys
If you prefer to explicitly look at the keys of each object:
var solution = jobs.filter(person => Object.keys(person).includes("programmer"));
Object.keys(person) returns an array of the object's keys, and we check if that array includes "programmer".
All of these will give you the expected result: [{programmer: "Steve"}]
Bonus: A More Scalable Data Structure
If you can adjust your data to use consistent keys (which is more common and easier to maintain), the code becomes even cleaner:
var jobs = [ {role: "receptionist", name: "James"}, {role: "programmer", name: "Steve"}, {role: "designer", name: "Alicia"} ]; var solution = jobs.filter(person => person.role === "programmer");
This makes filtering, mapping, and manipulating the data much more intuitive down the line.
内容的提问来源于stack exchange,提问作者PBandJ333

