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

时间:2020-07-28 14:45:06

标签: node.js express

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

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 个答案:

答案 0 :(得分:1)

问题是您通过配方对象对indexOf的调用未在数组中找到元素,因此它返回了-1。查看这段代码的工作原理:

let x = [{id: 1}, {id: 2}, {id: 3}]
let obj = {id: 2}
let i = x.indexOf(obj)
// i is -1 since obj isn't in the array. 
// Another object that looks like obj is there, 
// but they aren't the same exact object
console.log("i=",i)  
// This will remove the last since splicing with -1 does that
x.splice( x.indexOf("d"), 1)
console.log(x)

// when the array has objects in it you can use `findIndex`
let y = [{id: 1}, {id: 2}, {id: 3}]
let j = y.findIndex(e => e.id === obj.id)
console.log("j=",j)
y.splice( j, 1 )
console.log(y)

因此,您要做的是找到一种可靠的方法来找到阵列中配方的索引。有关如何在对象内查找索引的信息,请参见第二个示例。 Array.findIndex可让您以特定于对象结构的方式比较对象。

答案 1 :(得分:0)

如果要从数组中删除对象,可以使用如下过滤方法:

user.recipes = user.recipes.filter(r => {
    return r !== recipe;
})
相关问题