I want to write a function which will return id from array of object but when i call that function it returns me what I pass.
export function getRecipeByID(requestId) {
recipes.find(function (recipe) {
return recipe.id === requestId;
});
return requestId;
}
for example I call function
getRecipeByID(1)
and it returns 1.
I guess what you want to write is this:
export function getRecipeByID(requestId) {
return recipes.find(function (recipe) {
return recipe.id === requestId;
});
}
Notice that it doesn't return requestId but the result of recipes.find()
you return requestId after using find which cause issue
const recipes = [
{
id: 2,
name: 'pasta'
},
{
id: 3,
name: 'sandwich'
},
{
id: 4,
name: 'pizza'
}
]
function getRecipeById(requestId) {
const findRecipe = recipes.find(function (recipe) {
return recipe.id === requestId;
});
return findRecipe;
}
console.log(getRecipeById(2)); // it will return{ id:2, name:"pasta" }
That's because you return requestId in your method while what you want is to return the result of recipes.find...
export function getRecipeByID(requestId) {
return recipes.find(function (recipe) {
return recipe.id === requestId;
});
}