0

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);`
2
  • 1
    find will loop over each item, until found, hence 2 times.. remove the comments, keep it simple const result = empArray.find(item => item.employee.employee_ID === E_ID), no function needed Commented Jan 9, 2023 at 22:00
  • Regarding changing find() to map(), the issue is the same... it will iterate over every entry Commented Jan 9, 2023 at 22:15

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, My task was by using a map(), find was used as I was learning to do it with find. I edited my code,
I can't think of any reasonable way to do this with map(). That returns a new array of the results of all the callbacks, it can't be used to select a specific element of the array.
More generally, you can't tell if the element is found during the iteration, you have to wait until the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.