0

I have following object:

{
  "_id": "583c4e054c99d310f543b11e",
  "cellphone": "123456",
  "password": "$2a$10$d3SeD5CCzTo6wBR/4SGUu.i7vUvX98N1NlpBTwDdWCRrIYcVwWmCO",
  "fullname": "some name",
  "gender": "male",
  "avatar": {
    "_id": "583c4e054c99d310f543b11d",
    "__v": 0,
    "url": "",
    "likesCount": 0,
    "description": "Hey guys"
  },
  "__v": 0
}

By next code I want to create a new object without properties from mongodb (__v) and with renaming _id to id.

  let plainUser = {
    id: user._id,
    ...user.toObject(),
  }

  delete plainUser._id;
  delete plainUser.password;
  delete plainUser.__v;
  delete plainUser.avatar._id;
  delete plainUser.avatar.__v;

  return res.send(plainUser);

I think I can make it differently. Any suggestions how can I properly improve my code with ES6?

Georgiy T.
  • 966
  • 8
  • 15

2 Answers2

2

Better be explicit about which properties to keep instead of specifying which ones should be removed. And delete is quite inefficient. So just go for

return res.send({
    id: user._id,
    cellphone: user.cellphone,
    fullname: user.fullname,
    gender: user.gender,
    avatar: {
        url: user.avatar.url,
        likesCount: user.avatar.likesCount,
        description: user.avatar.description
    }
});

For some simplification, have a look at the approach from One-liner to take some properties from object in ES 6:

const {_id: id, cellphone, fullname, gender} = user;
const avatar = (({url, likesCount, description}) => ({url, likesCount, description}))(user.avatar);
return res.send({id, cellphone, fullname, gender, avatar});
Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
0

Here is a function that will normalize the object properties:

function normalizeObjectKeys(obj) {
    let normilizedObj = {};
    Object.keys(obj).map(key => {
        let newKey = key.replace(/_+/, '');
        normilizedObj[newKey] = ('object' !== typeof obj[key]) ? obj[key] : normalizeObjectKeys(obj[key]);
    });
    return normilizedObj;
}

Example:

normalizeObjectKeys({
  "_id": "583c4e054c99d310f543b11e",
  "cellphone": "123456",
  "password": "$2a$10$d3SeD5CCzTo6wBR/4SGUu.i7vUvX98N1NlpBTwDdWCRrIYcVwWmCO",
  "fullname": "some name",
  "gender": "male",
  "avatar": {
    "_id": "583c4e054c99d310f543b11d",
    "__v": 0,
    "url": "https://pp.vk.me/c631525/v631525614/2b398/kbI5QohgEgQ.jpg",
    "likesCount": 0,
    "description": "Hey guys"
  },
  "__v": 0
});
i--
  • 4,211
  • 2
  • 24
  • 35