如何从过滤后的数组中提取单个参数赋值给变量?
解决方案
一、优化你现有filter代码的用法
你当前用filter得到的是匹配结果组成的数组(哪怕只有一个匹配项),所以需要从数组里取出第一个元素,再提取它的startDate属性:
var employeeName = 'John McCully'; const employeeChart = [{Name : 'John McCully', Email : 'jmccully@domain.com', startDate : '04/20/2023'}, {Name : 'Thomas Young', Email : 'Tyoung@domain.com', startDate : '04/30/2023'}]; // 先过滤出匹配的员工数组 var matchedEmployees = employeeChart.filter(emp => emp.Name === employeeName); // 判断数组是否有内容,再提取startDate,避免找不到时报错 var employeeStartDate = matchedEmployees.length > 0 ? matchedEmployees[0].startDate : '未找到该员工'; console.log(employeeStartDate); // 输出: 04/20/2023
二、更适合的find方法(推荐)
因为你要找的是单个员工(默认员工姓名唯一),用find方法更高效——它找到第一个匹配项后就会停止遍历,直接返回匹配的对象,不用处理数组:
var employeeName = 'John McCully'; const employeeChart = [{Name : 'John McCully', Email : 'jmccully@domain.com', startDate : '04/20/2023'}, {Name : 'Thomas Young', Email : 'Tyoung@domain.com', startDate : '04/30/2023'}]; // 直接找到匹配的员工对象 var matchedEmployee = employeeChart.find(emp => emp.Name === employeeName); // 用可选链?.防止找不到员工时报错,|| 设置默认值 var employeeStartDate = matchedEmployee?.startDate || '未找到该员工'; console.log(employeeStartDate); // 输出: 04/20/2023
补充说明
- 如果能确保目标员工一定存在于数组中,可以简化为
var employeeStartDate = employeeChart.find(emp => emp.Name === employeeName).startDate; - 把函数参数名从
employeeChart改成emp是为了避免和数组名重名,代码更清晰易读。
内容的提问来源于stack exchange,提问作者Thomas Young
相关产品推荐
相关产品推荐

