How can I check that two objects have the same set of property names?

后端 未结 7 1301
傲寒
傲寒 2020-11-28 06:04

I am using node, mocha, and chai for my application. I want to test that my returned results data property is the same \"type of object\" as one of my model objects (Very si

7条回答
  •  甜味超标
    2020-11-28 06:21

    2 Here a short ES6 variadic version:

    function objectsHaveSameKeys(...objects) {
       const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
       const union = new Set(allKeys);
       return objects.every(object => union.size === Object.keys(object).length);
    }
    

    A little performance test (MacBook Pro - 2,8 GHz Intel Core i7, Node 5.5.0):

    var x = {};
    var y = {};
    
    for (var i = 0; i < 5000000; ++i) {
        x[i] = i;
        y[i] = i;
    }
    

    Results:

    objectsHaveSameKeys(x, y) // took  4996 milliseconds
    compareKeys(x, y)               // took 14880 milliseconds
    hasSameProps(x,y)               // after 10 minutes I stopped execution
    

提交回复
热议问题