0

I have two objects with multiple properties and with multiple layers. At different layers, I might have some arrays. I want to be able to compare the two objects, disregarding the ordering of elements in each array.

Example 1: object1 and object2 should be "equal"

object1 = {
    person: "John",
    children: [
        {
            person: "Anne"
        },
        {
            person: "Mark"
        }
    ]
};

object2 = {
    person: "John",
    children: [
        {
            person: "Mark"
        },
        {
            person: "Anne"
        }
    ]
};

// This would have to return true:
expect(object1).to."fundamentally".equal(object2);

Example2: a bit more complicated, object1 and object2 should still be the same

object1 = {
    person: "John",
    children: [
        {
            person: "Anne"
        },
        {
            person: "Mark",
            pets: [
                {
                    species: "cat",
                    name: "Purr"
                },
                {
                    type: "labrador",
                    name: "Woofy",
                    age: 3
                }

            ]
        }
    ],
    cars: [
        {
            brand: "BMW",
            year: 2017
        },
        {
            brand: "Mercedes-Benz",
            year: 2020
        }

    ]
};

object2 = {
    person: "John",
    children: [
        {
            person: "Mark",
            pets: [
                {
                    type: "labrador",
                    name: "Woofy",
                    age: 3
                },
                {
                    species: "cat",
                    name: "Purr"
                }

            ]
        },
        {
            person: "Anne"
        }
    ],
    cars: [
        {
            brand: "Mercedes-Benz",
            year: 2020
        },
        {
            brand: "BMW",
            year: 2017
        }

    ]
};



// This would have to return true:
expect(object1).to."fundamentally".equal(object2);

Even though the children, cars and pets are in different order, I still want to recognize that both objects have the same contents.

Is there a function that would do this?

Cavarica2
  • 25
  • 6
  • Does this answer your question? [Expect Arrays to be equal ignoring order](https://stackoverflow.com/questions/32103252/expect-arrays-to-be-equal-ignoring-order) – ziishaned Oct 27 '21 at 08:16
  • I don't believe it does, just because the arrays might be at any level of the object, and it's not necessary that the array elements conform to a structure - they don't all need to have a common "id" field by which they could be sorted. Please correct me if I'm wrong. – Cavarica2 Oct 27 '21 at 09:26

0 Answers0