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

后端 未结 7 1299
傲寒
傲寒 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:24

    Here is my attempt at validating JSON properties. I used @casey-foster 's approach, but added recursion for deeper validation. The third parameter in function is optional and only used for testing.

    //compare json2 to json1
    function isValidJson(json1, json2, showInConsole) {
    
        if (!showInConsole)
            showInConsole = false;
    
        var aKeys = Object.keys(json1).sort();
        var bKeys = Object.keys(json2).sort();
    
        for (var i = 0; i < aKeys.length; i++) {
    
            if (showInConsole)
                console.log("---------" + JSON.stringify(aKeys[i]) + "  " + JSON.stringify(bKeys[i]))
    
            if (JSON.stringify(aKeys[i]) === JSON.stringify(bKeys[i])) {
    
                if (typeof json1[aKeys[i]] === 'object'){ // contains another obj
    
                    if (showInConsole)
                        console.log("Entering " + JSON.stringify(aKeys[i]))
    
                    if (!isValidJson(json1[aKeys[i]], json2[bKeys[i]], showInConsole)) 
                        return false; // if recursive validation fails
    
                    if (showInConsole)
                        console.log("Leaving " + JSON.stringify(aKeys[i]))
    
                }
    
            } else {
    
                console.warn("validation failed at " + aKeys[i]);
                return false; // if attribute names dont mactch
    
            }
    
        }
    
        return true;
    
    }
    

提交回复
热议问题