Search code examples
javascriptjqueryqunit

Javascript how to remove prototype methods from a data object or make objects work with Qunit equals


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?


Solution

  • 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.