简体   繁体   中英

How can I remove a property of object from an array in Mongoose? !Important

Doc -

const array =   [
  {
    user: new ObjectId("627913922ae9a8cb7a368326"),
    name: 'Name1',
    balance: 0,
    _id: new ObjectId("627913a92ae9a8cb7a36832e")
  },
  {
    user: new ObjectId("6278b20657cadb3b9a62a50e"),
    name: 'Name2',
    balance: 0,
    _id: new ObjectId("6279133b2ae9a8cb7a368314")
  },
  {
    user: new ObjectId("627913692ae9a8cb7a368319"),
    name: 'Name3',
    balance: 0,
    _id: new ObjectId("627913872ae9a8cb7a368321")
  },
  {
    user: new ObjectId("6278b24e57cadb3b9a62a513"),
    name: 'Name4',
    balance: 0,
    _id: new ObjectId("6278b41ab18ff3dff84781bd")
  }
]

Here, I want to remove the "_id" from all the objects in the array

I tried to use delete property but it didn't work

array.forEach(object=>delete object._id)

And When I tried the same array.forEach(object=>delete object._id) by removing new ObjectId in _id property of object in array it worked fine!

But as I am fetching this array from MongoDb,I can't remove this new ObjectId manually, So I need to fix this!!

Here, I got my answer

In the array

    const array =   [
  {
    user: new ObjectId("627913922ae9a8cb7a368326"),
    name: 'Name1',
    balance: 0,
    _id: new ObjectId("627913a92ae9a8cb7a36832e")
  },
  {
    user: new ObjectId("6278b20657cadb3b9a62a50e"),
    name: 'Name2',
    balance: 0,
    _id: new ObjectId("6279133b2ae9a8cb7a368314")
  },
  {
    user: new ObjectId("627913692ae9a8cb7a368319"),
    name: 'Name3',
    balance: 0,
    _id: new ObjectId("627913872ae9a8cb7a368321")
  },
  {
    user: new ObjectId("6278b24e57cadb3b9a62a513"),
    name: 'Name4',
    balance: 0,
    _id: new ObjectId("6278b41ab18ff3dff84781bd")
  }
]

I tried to use.map() and it did my work

let list = []

array.map((object)=>{
    list.push({user: object.user,name: object.name,balance: object.balance})
})

console.log(list);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM