Home > Net >  I am trying to make a function which will return an id from array of object
I am trying to make a function which will return an id from array of object

Time:12-10

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.

CodePudding user response:

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()

CodePudding user response:

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

CodePudding user response:

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" }

CodePudding user response:

Try this:

export function getRecipeByID(requestId) {
  const recipe = recipes.find(item => item.id === requestId);
  if (recipe && recipe.id) {
    return recipe.id;
  } else {
    return null;
  }
}

Explanation: You're not assigning the result of the find operation (the element that has been found or null if there was no matching element) to any variable and are simply returning the request id.

Also: I'd suggest you'd look into arrow functions. They have been available for some years now and make your code much easier to read. :)

CodePudding user response:

If you really want a function that return the same Id that you fetch, then do it:

export function getRecipeByID(requestId) {
      return requestId;
      
    } 

otherwise, if want to fetch an Object of your list of object then you can simply try:

const array1 = [{}]
export function getRecipeByID(requestId) {
          return array1.find(element => element.id == requestId);
          
        } 
  • Related