Home > Software design >  Map function in JSON array
Map function in JSON array

Time:01-10

I want to find an object from a JSON array. My code is working fine with the object found. But the issue is what if the employee id is not? My code console's "not found" two times. Kindly guide me on what the issue is with my code.

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);`

CodePudding user response:

The if statement should not be inside find(). find() will return the matching element, or null if it's not found. So test the return value.

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;
    }
}
  • Related