Sangram Singh
Sangram Singh

Reputation: 7191

NOT using reference to object (javascript)

The below :-

req.session.user = doc[0];
req.session.user.password = null;

Makes doc[0].password = null!

What do i do to prevent that?

Edit: Where doc[0] = { name: 'sangram', e-mail: 'abc.in', password : 'pwd' }

Upvotes: 0

Views: 42

Answers (4)

Krasimir
Krasimir

Reputation: 13539

You can't prevent this. The user property is set to that object doc[0]. Later you edit .password property of that newly assigned object. If you want to keep the password separately you have to assign doc[0] to another object.

req.session.user = {};
req.session.user.doc = doc[0];
req.session.user.password = null;

Here is a method for cloning/extending an object:

var extend = function() {   
    var process = function(destination, source) {   
        for (var key in source) {
            if (hasOwnProperty.call(source, key)) {
                destination[key] = source[key];
            }
        }
        return destination;
    };
    var result = arguments[0];
    for(var i=1; i<arguments.length; i++) {
        result = process(result, arguments[i]);
    }
    return result;
};

And its usage:

var original = { value: "bla" };
var duplication = extend({}, original, { newProp: "test"});

Upvotes: 0

Ted Johnson
Ted Johnson

Reputation: 4343

I would recommend updating or changing your question in the future.

What is the most efficient way to deep clone an object in JavaScript? How do I correctly clone a JavaScript object?

Crockford provides a very good answer here

Upvotes: 0

Shadow Wizzard
Shadow Wizzard

Reputation: 66388

For simple case of simple objects, I wrote a small helper function:

function ShallowClone(obj) {
    var clone = {};
    for (var key in obj)
        clone[key] = obj[key];
    return clone;
}

Usage in your case:

req.session.user = ShallowClone(doc[0]);
req.session.user.password = null; //won't affect doc[0] password

Live test case. (with dummy object)

Upvotes: 2

Leonid Beschastny
Leonid Beschastny

Reputation: 51490

The only way to do so is to copy every property of an object:

req.session.user = {};
for (var key in user) {
  if (key !== 'password') req.session.user[key] = user[key];
}

If user is a mongoose document, you probably should convert it to plain object first:

req.session.user = {};
var json = user.toObject();
for (var key in json) {
  if (key !== 'password') req.session.user[key] = json[key];
}

But the easiest way to do what you want is to adopt some helpful library like underscore or lodash:

req.session.user = _.omit(user.toObject(), 'password');

Upvotes: 2

Related Questions