I have the following function based on Node-Express:
//function on server side
app.get('/loginCheck', loggedCheck, function(req, res) {
var data = {local: {}, facebook: {}};
data.id = req.user._id;
data.local.email = req.user.local.email;
data.local.fname = req.user.local.fname;
data.local.lname = req.user.local.lname ;
data.local.college = req.user.local.college ;
data.local.degree = req.user.local.degree ;
data.year = req.user.year ;
data.mobile = req.user.mobile ;
data.city = req.user.city ;
data.facebook.id = req.user.facebook.id ;
//res.json(data);
var x = {};
x.name = "someName"
res.json(x);
})
Following is the code on client side which makes an ajax requests:
//function on client side making an ajax request
$.get("/loginCheck",function(data,status){
console.log(data);
});
In the former code on server side, req.user
is a mongodb object created by mongoose. What I want to do is send the data object (which has some selected attributes of req.user
object) and send the object as JSON as response.
The variable x
is a custom created variable.
The problem is:
When I send the data
object to client, __proto__
attribute is also added with the object which is not happening when I am sending x
to the client.
But, I don't want the __proto__
in the client side, because, from some articles, I found that there are security issues with __proto__
.
I need help on how to remove __proto__
from the data
object.
You can forego a prototype on an object simply by using Object.create(null)
and defining the properties you wish to use.
var obj = Object.create(null);
Object.defineProperty(obj, {
'foo': {
value: 1,
enumerable: true,
},
'bar': {
value: 2,
enumerable: false
}
});
// or...
obj.foo = 1
obj.bar = 2
/* various checks */
obj instanceof Object; // false
Object.prototype.isPrototypeOf(obj); // false
Object.getPrototypeOf(obj); // null
obj + ""; // TypeError: Cannot convert object to primitive value
'toString' in obj; // false
foo; // 1
obj['bar']; // 2
JSON.stringify(obj); // {"foo":1}
{}.hasOwnProperty.call(obj, 'foo'); // true
{}.propertyIsEnumerable.call(obj, 'bar'); // false
And in this approach, you no longer need to check for obj.hasOwnProperty(key)
for (var key in obj) {
// do something
}
Read More: True Hash Maps in JavaScript
MDN: Object.defineProperty() & Object.create()
// with __proto__
var obj = {} // equivalent to Object.create(Object.prototype);
obj.key = 'value'
console.log(obj)
// without __proto__
var bareObj = Object.create(null)
Object.defineProperty(bareObj, {
'key': {
value: 'value',
enumerable: false,
configurable: true,
writable: true
}
})
// or... bareObj.key = 'value'
console.log(bareObj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With