简体   繁体   English

使用 map 从数组中删除 object

[英]Delete object from array using map

I have an API call to get all the users of my application.我有一个 API 电话来获取我的应用程序的所有用户。 I have a problem, that the getAll method returns each users's password encrypted.我有一个问题,getAll 方法返回每个用户的加密密码。 I don't want to return the password.我不想返回密码。

That's my method:那是我的方法:

async getAll(pagination) {
    try {
      const { UserAdmin: userAdminSchema } = this.getSchemas();
      let usersAdmins = await userAdminSchema.paginate({}, {
        sort: { created: 'desc' },
        limit: pagination.limit ? parseInt(pagination.limit) : 10,
        page: pagination.page ? parseInt(pagination.page) + 1 : 1,
      });
      if (!usersAdmins) {
        throw new errors.NotFound('No UserAdmins found.');
      }
      usersAdmins.docs.map(async (u) => {
        delete u.password;
      });
      return usersAdmins
    } catch (error) {
      throw error;
    }
{
  "docs": [
    {
      "roles": [
        "Admin",
        "Read",
        "Modify",
      ],
      "_id": "5ffecc12a687a30580239a10",
      "name": "john",
      "email": "john@gmail.com",
      "password": "$2a$10$K6oKiiWKsIWmAGgkG7TmH.WjVpraNg45Uc0nber3FnF26oEzdgTS2",
      "created": "2021-01-13T10:31:46.982Z",
      "__v": 0
    },
    {
      "roles": [
        "Read"
      ],
      "_id": "5ffea1f1dd60b80718af6e3b",
      "name": "Megan",
      "email": "megan@gmail.com",
      "password": "$2a$10$V8ARIjxhEHCC1COcvtQEmOZ3IfXm5oiANdLmyHyipy1GmWSD3ctWK",
      "created": "2021-01-13T07:32:01.665Z",
      "__v": 0
    },
  ],
  "totalDocs": 2,
  "limit": 10,
  "totalPages": 1,
  "page": 1,
  "pagingCounter": 1,
  "hasPrevPage": false,
  "hasNextPage": false,
  "prevPage": 1,
  "nextPage": null
}

I just want to the delete the password.我只想删除密码。 How I can achieve this?我怎样才能做到这一点? The map I have done, still returns the password:我做的map,还是返回密码:

 usersAdmins.docs.map(async (u) => {
     delete u.password;
 });

I suspect the objects in your array are immutable, which is why your code didn't work.¹我怀疑您数组中的对象是不可变的,这就是您的代码不起作用的原因。¹

Instead, create and return a new object, and use the array that map returns:相反,创建并返回一个新的 object,并使用map返回的数组:

return {
    ...usersAdmins,
    docs: usersAdmins.docs.map(
        u => Object.fromEntries(Object.entries(u).filter(([key]) => key !== "password"))
    )
};

Live Example:现场示例:

 const usersAdmins = { "docs": [ { "roles": [ "Admin", "Read", "Modify", ], "_id": "5ffecc12a687a30580239a10", "name": "john", "email": "john@gmail.com", "password": "$2a$10$K6oKiiWKsIWmAGgkG7TmH.WjVpraNg45Uc0nber3FnF26oEzdgTS2", "created": "2021-01-13T10:31:46.982Z", "__v": 0 }, { "roles": [ "Read" ], "_id": "5ffea1f1dd60b80718af6e3b", "name": "Megan", "email": "megan@gmail.com", "password": "$2a$10$V8ARIjxhEHCC1COcvtQEmOZ3IfXm5oiANdLmyHyipy1GmWSD3ctWK", "created": "2021-01-13T07:32:01.665Z", "__v": 0 }, ], "totalDocs": 2, "limit": 10, "totalPages": 1, "page": 1, "pagingCounter": 1, "hasPrevPage": false, "hasNextPage": false, "prevPage": 1, "nextPage": null }; const result = {...usersAdmins, docs: usersAdmins.docs.map( u => Object.fromEntries(Object.entries(u).filter(([key]) => key;== "password")) ) }. console;log(result);


¹ Re your original code: ¹ 重新您的原始代码:

  1. The async is pointless, none of the code in your callback is using await (nor does it need to) async是没有意义的,回调中的代码都没有使用await (也不需要)
  2. using map but not using the array it creates is an anti-pattern.使用map但不使用它创建的数组是一种反模式。 If you don't need the result array, use forEach or a for-of loop or just a for loop.如果不需要结果数组,请使用forEachfor-of循环或仅使用for循环。 (But here I suspect we do need to use the array that map produces.) (但在这里我怀疑我们确实需要使用map生成的数组。)

If you are using Mongoose lib for model User, declare the password field like this would solve your problem.如果您为 model 用户使用 Mongoose lib,声明密码字段可以解决您的问题。

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Please add a name']
    },
    email: {
        type: String,
        required: [true, 'Please add an email'],
        unique: true,
        match: [
            /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
            'Please add a valid email'
        ]
    },
    role: {
        type: String,
        enum: ['user', 'publisher'],
        default: 'user'
    },
    password: {
        type: String,
        required: [true, 'Please add a password'],
        minlength: 6,
        select: false // <=== IMPORTANT
    }
});

It means that password would not be returned whenever you get Users.这意味着无论何时获得用户,都不会返回密码。

you can create a new object in map and return that, or set the password to the empty string with Object.assign您可以在 map 中创建一个新的 object 并返回它,或者使用 Object.assign 将密码设置为空字符串

 const data = [{ "roles": [ "Admin", "Read", "Modify", ], "_id": "5ffecc12a687a30580239a10", "name": "john", "email": "john@gmail.com", "password": "$2a$10$K6oKiiWKsIWmAGgkG7TmH.WjVpraNg45Uc0nber3FnF26oEzdgTS2", "created": "2021-01-13T10:31:46.982Z", "__v": 0 }, { "roles": [ "Read" ], "_id": "5ffea1f1dd60b80718af6e3b", "name": "Megan", "email": "megan@gmail.com", "password": "$2a$10$V8ARIjxhEHCC1COcvtQEmOZ3IfXm5oiANdLmyHyipy1GmWSD3ctWK", "created": "2021-01-13T07:32:01.665Z", "__v": 0 }, ]; const dataWithOutPassword = data.map((user) => { return { roles: user.roles, _id: user._id, name: user.name, email: user.email, created: user.created } }); console.log(dataWithOutPassword); const dataWithOutPassword2 = data.map((user) => { return Object.assign({}, user, { password: '' }) }); console.log(dataWithOutPassword2)

in paginate function you can select every fields that you need with select property, like following code:在分页 function 中,您可以使用select属性 select 您需要的每个字段,如以下代码:

await userAdminSchema.paginate({}, {
       select: "name email",
        sort: { created: 'desc' },
        limit: pagination.limit ? parseInt(pagination.limit) : 10,
        page: pagination.page ? parseInt(pagination.page) + 1 : 1,
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 例如,克隆对象、映射或数组然后使用删除是否被认为是不可变的? - Is cloning an object, map or array and then using delete for example, considered immutable? 如何使用 Cloud Functions 从 Firestore 中的 ArrayList Map 中删除 object? - How to delete an object from an ArrayList Map in Firestore using Cloud Functions? 如何使用对象属性从数组中删除对象 - React - How to delete object from array using object property - React 使用 for 循环从数组中删除 object 而不影响数组的 rest - Using a for loop to delete an object from an array without affecting the rest of the array 如何使用angularjs从对象数组中删除项目? - How to delete item from an array of object using angularjs? 使用mongoose从mongodb集合中的文档数组中删除对象 - delete object from document array in mongodb collection using mongoose 使用可变属性值从JavaScript数组中删除对象 - Delete object from javascript array using variable property value 想要使用 Sequelize 从 object 数组中删除任务 - want to delete a task from an array of object using Sequelize 如何在 React 中使用 JavaScript 从数组中删除 object 元素 - How to delete object element from an array using JavaScript in React 使用 delete() 从数组中删除 object,并在 TextField 中呈现对象名称 - Using delete() to remove object from array, and render the objects name in a TextField
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM