如何在javascript中断言部分深度相等/比较对象?

Mic*_*arf 5 javascript

我有一个API,我想断言至少返回预期的数据.我不在乎是否返回更多数据.

因此,我想比较两个对象(expectedactual),其中所有属性expected必须等于actual,但actual可能包含更多属性:

var expected = {
    foo: 1,
    bar: {
        x1: 42,
        a1: [
            1,
            2,
            {
                x: 7
            }
        ]
    }
}

var actual = {
    foo: 1,
    whatever: 55, // to be ignored
    additional: { // to be ignored
        ignore: 1
    },
    bar: {
        x1: 42,
        a1: [
            1,
            2,
            {
                x: 7,
                y: 8   // to be ignored
            }
        ]
    }
}

partiallyEqual(expected, actual) // returns true
Run Code Online (Sandbox Code Playgroud)

更多例子:

partiallyEqual({x: 1}, {a:2, x:1}) // return true
partiallyEqual({x: 1}, {a:2, x:2}) // return false (x is different)
Run Code Online (Sandbox Code Playgroud)

如果actual包含其他元素,则阵列可以(可选地)受到部分等效.

partiallyEqual([1, 3], [1, 2, 3]) // return true
partiallyEqual([3, 1], [1, 2, 3]) // return false (different order)
Run Code Online (Sandbox Code Playgroud)

Akx*_*kxe -1

我使用我前段时间写的这个递归函数:

Object.prototype.equals = function(to) {
    for (var prop in to) {
        if (this.hasOwnProperty(prop) && to.hasOwnProperty(prop)) {
            if (to[prop] && typeof this[prop] == "object" && typeof to[prop] == "object") {
                if (!this[prop].equals(to[prop])) {
                    return false
                }
            } else if (this[prop] != to[prop]) {
                return false
            }
        }
    }
    return true;
};

({ x: { a: 1, b: 2 } }).equals({ x: { a: 1, b: 2 } }) => true
({ x: { a: 1, b: 2 } }).equals({ x: { a: 1, b: 1 } }) => false
({ x: [1,2] }).equals({ x: { 1:1,2:2 } }) => true (doesn't differentiate between array and/or object)
Run Code Online (Sandbox Code Playgroud)

一旦发现旧对象与新对象存在差异,该函数将立即返回 false。如果新对象具有旧对象的所有属性,则它可以包含任何内容。