You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合ES6箭头函数使用filter()筛选程序员职业对象?

如何用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:

  1. 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).

  1. Use Object.hasOwn() (recommended over in for 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.

  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:23:51