I've started working with Qunit to do unit testing on my code, but am striking problems comparing objects.
The code I'm testing dynamically creates an object:
var fields = ['id','name'];
var result = {};
for (var field in fields)
{
var name = fields[field];
result[name] = name;
}
var expected = { id : 'id', name : 'name' };
test(expected, result, "same ?");
This test fails, and I can see that while expected just contains the fields id and name, result also contains a whole lot of functions, eg
"function (iterator, context) {...
I think these functions come from me treating the object like an array in order to assign to it.
Is there a way to strip these functions out (or prevent them from getting added in the first place)?
I was thinking of doing
result = $.parseJSON($.toJSON(result));
is there a better way?
setPrototypeOf() The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null .
The solution is to create an object without a prototype: var dict = Object. create(null);
The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.
prototype. __proto__ Deprecated: This feature is no longer recommended.
You can check the type of each object in the collection to see if it's a function:
if(typeof fields[field] == 'function') continue;
Also, don't use for..in
on arrays:
for(var i = 0; i < fields.length; i++) {
result[result[i]] = result[i];
}
What you have there isn't strictly an object, it's an Array
object, which is nevertheless an object, but not in the sense that it has key-value pairs.
If you use a vanilla for
loop, you will not iterate through the prototype chain as you do with for..in
, so maybe doing that might solve your problem.
The problem is your use of for...in
, which is iterating over everything fields
is inheriting from object
. If you must keep for...in
, you can modify it like this:
for (var field in fields){
if( fields.hasOwnProperty( field ) ){
var name = fields[field];
result[name] = name;
}
}
hasOwnProperty
returns true if the specified property of the object (and the array is an object) is not inherited.
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