Skip to content Skip to sidebar Skip to footer

Comparing Two Json Objects

I'm trying to find a faster way to compare two json objects. Currently, we have a function that has about 7 $.each() calls in it, which I believe is a very inefficient way to do th

Solution 1:

Here's a function that recursively collects all properties in two objects and then returns you an array of any common property names between them. If .length === 0 in the returned array, then there are no common properties. Otherwise, it contains the common property names. If you need to do any further checking, you can obviously add more specifics to this fairly generic function.

If you need to know where the common prop is in the two object, you could change the map to save the parent object instead of just setting it to true, but then you'd have to deal with the issue where there were more than one occurrence of that property. I didn't go to that level of detail because your specification for what you want to do isn't detailed so I left it here with a function that shows how to recursively walk through all properties in an object.

functionfindCommonProps(obj1, obj2) {
    var map1 = {}, map2 = {};
    var commonProps = [];

    functionisArray(item) {
        returnObject.prototype.toString.call(item) === "[object Array]";
    }

    functiongetProps(item, map) {
        if (typeof item === "object") {
            if (isArray(item)) {
                // iterate through all array elementsfor (var i = 0; i < item.length; i++) {
                    getProps(item[i], map);
                }
            } else {
                for (var prop in item) {
                    map[prop] = true;
                    // recursively get any nested props// if this turns out to be an object or arraygetProps(item[prop], map);
                }
            }
        }
    }

    // get all properties in obj1 into a mapgetProps(obj1, map1);
    getProps(obj2, map2);
    for (var prop in map1) {
        if (prop in map2) {
            commonProps.push(prop);
        }
    }
    return commonProps;
}

Working demo: http://jsfiddle.net/jfriend00/ESBZv/

Post a Comment for "Comparing Two Json Objects"