I have an array of "shirt" objects:
const shirts = [
{
id: 241,
title: Shirt One
},
{
id: 126,
title: Shirt Two
}
]
How can I get the title value using the id?
I have an array of "shirt" objects:
const shirts = [
{
id: 241,
title: Shirt One
},
{
id: 126,
title: Shirt Two
}
]
How can I get the title value using the id?
First of all, you have to wrap your strings in single quotes, double quotes, or backticks.
The naive solution here would be to loop through the shirt objects and pick the one with the matching id, like this:
function getTitleFromId(shirts, id) {
for (let i = 0; i < shirts.length; i++) {
if (shirts[i].id === id) return shirts[i].title;
}
return '';
}
However, this isn't the best way to solve the problem. The best way to do this would be to use Array.prototype.find. Here is an example:
function getTitleFromId(shirts, id) {
return shirts.find(shirt => shirt.id === id)?.title ?? '';
}
Try this approach,
const shirts = [
{
id: 241,
title: 'Shirt One'
},
{
id: 126,
title: 'Shirt Two'
}];
const getTitleById = (shirts, id) => shirts.find(shirt => shirt.id === id)?.title || "";
getTitleById(shirts, 241); // Shirt One