【问题标题】:Node JS remove a specific object from array (mongoose)Node JS 从数组中删除特定对象(猫鼬)
【发布时间】:2021-12-18 21:39:30
【问题描述】:

我有一个对象数组 - 列表[];和一个对象 - obj;

这是列表数组:

{
  _id: new ObjectId("61840c5ce237f22a1c7a1ac7"),
  name: 'list1',
  content: [ 'aaaa' ],
  description: 'aa',
  tags: [],
  lastmodified: 1,
  __v: 0
},{
  _id: new ObjectId("61840def80a88d1b2ffce400"),
  name: 'list',
  content: [ 'list!' ],
  description: 'test',
  tags: [],
  __v: 0
}

这是 obj 对象:

{
  _id: new ObjectId("61840def80a88d1b2ffce400"),
  name: 'list',
  content: [ 'list!' ],
  description: 'test',
  tags: [],
  __v: 0
}

简单问题:如何从“列表”中删除对象,类似于“obj”之一

【问题讨论】:

标签: node.js arrays mongodb mongoose


【解决方案1】:

使用某种过滤...这是一个想法。

items = [{
  _id: new ObjectId("61840c5ce237f22a1c7a1ac7"),
  name: 'list1',
  content: [ 'aaaa' ],
  description: 'aa',
  tags: [],
  lastmodified: 1,
  __v: 0
},{
  _id: new ObjectId("61840def80a88d1b2ffce400"),
  name: 'list',
  content: [ 'list!' ],
  description: 'test',
  tags: [],
  __v: 0
}]

removeID = "61840def80a88d1b2ffce400"

items = [item for item in items if item['id'] != removeID]

【讨论】:

    【解决方案2】:

    您可以使用 JavaScript Array.filter() 方法从列表中排除目标对象:

    const list = [{
    _id: new ObjectId("61840c5ce237f22a1c7a1ac7"),
      name: 'list1',
      content: [ 'aaaa' ],
      description: 'aa',
      tags: [],
      lastmodified: 1,
      __v: 0
    },{
      _id: new ObjectId("61840def80a88d1b2ffce400"),
      name: 'list',
      content: [ 'list!' ],
      description: 'test',
      tags: [],
      __v: 0
    }];
    
    const targetObj = {
      _id: new ObjectId("61840def80a88d1b2ffce400"),
      name: 'list',
      content: [ 'list!' ],
      description: 'test',
      tags: [],
      __v: 0
    };
    
    const filteredList = list.filter((element) => element._id !== targetObj._id);
    

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2017-03-28
      • 1970-01-01
      • 2020-10-19
      • 2017-10-23
      • 1970-01-01
      相关资源
      最近更新 更多