Ayush Gupta
Ayush Gupta

Reputation: 1727

Object declaration in Javascript

I have the following code. Now when the constructor is called, the object gets created. Now when updating the field they are being updated like this. Note that I cannot modify the Comment() because it is created by mongoose.

  var newComment = new Comment();
  newComment.content = req.body.content;
  newComment.user.id = req.body.id;
  newComment.user.name = req.body.name;
  newComment.user.profilePicture = req.user.profilePicture;
  newComment.votes.up = [];
  newComment.votes.down = [];
  newComment.comments = [];
  newComment.timestamp = Date.now();

Is there a way to do something to update the object like this:

newComment.SOMEFUNCTION({
  content = req.body.content;
  user.id = req.body.id;
  user.name = req.body.name;
  user.profilePicture = req.user.profilePicture;
  votes.up = [];
  votes.down = [];
  comments = [];
  timestamp = Date.now();
});

Upvotes: -1

Views: 60

Answers (2)

pawel
pawel

Reputation: 37005

Object.assign

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

Object.assign( newComment, {
    content : req.body.content,
    user : {
      id : req.body.id,
      name : req.body.name,
      profilePicture : req.user.profilePicture
    },
  votes.up : [],
  votes.down : [],
  comments : [],
  timestamp : Date.now()
});

http://jsfiddle.net/r8pavnuv/

Upvotes: 3

Michael Fourre
Michael Fourre

Reputation: 3015

What's the reason for doing this? Is it just for organization purposes? If so then what's stopping you from just making a separate function:

var newFunc = function(newComment){
  newComment.content = req.body.content;
  newComment.user.id = req.body.id;
  newComment.user.name = req.body.name;
  newComment.user.profilePicture = req.user.profilePicture;
  newComment.votes.up = [];
  newComment.votes.down = [];
  newComment.comments = [];
  newComment.timestamp = Date.now();
};

You won't be able to safely change the Comment class, so if your intent is to maintain organization then this is a reasonable approach to keep from cluttering your constructor method

Upvotes: 1

Related Questions