我想从JSON数组中找到一个对象。我的代码工作良好的对象发现。但问题是,如果员工id不是呢?我的代码控制台"未找到"两次。请指导我的问题是什么与我的代码。
var E_ID
let empArray = [
{
"employee": {
"employee_ID": 16,
"employee_designation": "Node.js",
"employee_FirstName": "John",
"employee_lastName": "Doe",
}
},
{
"employee": {
"employee_ID": 17,
"employee_designation": "Full Stack",
"employee_FirstName": "Samual",
"employee_lastName": "Smith",
},
}
]
function search_EmployeeByID(E_ID) {
empArray.map(item => {
if (item.employee.employee_ID == E_ID) {
console.log(item.employee)
return true
}else {
console.log("not found")
return false
}
})
}
E_ID = parseInt(prompt("Enter Employee_ID to search for:"))
search_EmployeeByID(E_ID);`
if
语句不应该在find()
中。find()
将返回匹配的元素,如果没有找到则返回null
。所以测试返回值。
function searchEmployeeByID(e_id) {
let emp = empArray.find(e => e.employee.employee_ID == e_id);
if (emp) (
console.log(emp.employee);
return true;
} else {
console.log("not found");
return false;
}
}