-1

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();
});

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.