I have an array of objects that looks like this:
contacts: [
{
id: 1,
name: "John Doe",
email: "[email protected]",
phone: "555-555-5555",
},
{
id: 2,
name: "Karen Williams",
email: "[email protected]",
phone: "444-444-4444",
},
{
id: 3,
name: "Henry Johnson",
email: "[email protected]",
phone: "333-333-333",
},
]
I want to loop through them and if one of their ID's matches the ID I am looking for then I need that return and assigned to another variable.
This is what I have so far but it tells me the selectedContact is undefined.
function getSingleContactFromId(contacts, id) {
contacts.forEach((contact) => {
console.log(contact);
if (contact.id == id) {
console.log(contact);
return { contact };
}
});
}
const selectedContact = getSingleContactFromId(contacts, id);
console.log(selectedContact);