提问者:小点点

如何从对象数组中拼接一个对象?


事情是,我正在为每个用户对象做一个收藏夹数组。 我做了插入请求到数组添加一些喜欢的食谱。 问题是当我想从数组中移除favorite时,它总是移除最后一个对象,而不是我想要的确切对象。

const recipe = await getRecipes(req.params.id); //gives the recipe object
 let user = await User.findById(req.user._id); // gives the user object
  
  console.log(recipe);
  user.recipes.splice(user.recipes.indexOf(recipe), 1);

  await user.save();
  res.send(user); 

共2个答案

匿名用户

问题是您对传递recipe对象的indexof的调用没有找到数组中的元素,因此它返回-1。 查看此代码的工作原理:

null

let x = ["a", "b", "c"]

let i = x.indexOf("d")
console.log(i)  // i is -1 since 'd' is not found
// This will remove the last since splicing with -1 does that
x.splice( x.indexOf("d"), 1)
console.log(x)

匿名用户

如果要从数组中移除对象,可以使用如下所示的filter方法:

user.recipes = user.recipes.filter(r => {
    return r !== recipe;
})