开发者

Most efficient way of finding differences (added & removed pairs) in two JavaScript hashes

I have two JavaScript hashes of string, objects called existingItems and newItems. I want to compare and extract which items have been added (are unique to newItems) and which have been removed (are unique to existingItems). I want the comparison to be on the key of each pair.

What is the most efficient way of doing this? Should I be sorting the items first? Should I extract the keys to arrays and work them alone?

Example hashes:

var existing = [];
existing.push(["456",{Ref:"456",Title:"ttt456",food:"soup"}]);
existing.p开发者_开发问答ush(["789",{Ref:"789",Title:"ttt789",color:"blue",duck:"sauce"}]);
existing.push(["abc",{Ref:"abc",Title:"tttabc",colour:"yellklow",duck:"sauce"}]);
existing.push(["xyz",{Ref:"xyz",Title:"tttabc",colour:"yellklow",duck:"sauce"}]);
existing.push(["123",{Ref:"123",Title:"ttt123",pet:"cat"}]);

var newits = [];
newits.push(["abc",{Ref:"abc",Title:"tttabc",food:"horse"}]);
newits.push(["456",{Ref:"456",Title:"ttt456",pet:"cat",color:"green",cat:"sauce"}]);
newits.push(["def",{Ref:"def",Title:"tttabc",noise:"moo"}]);


var itemsAdded = compareHash(existing,newits);
var itemsRemoved =compareHash(newits,existing); 


These are not hashes, they’re arrays! (In Javascript, objects are hashes).

It could be done much more efficiently if you rewrote them like this:

var existing = {};
existing["456"] = {Ref:"456",Title:"ttt456",food:"soup"};
existing["789"] = {Ref:"789",Title:"ttt789",color:"blue",duck:"sauce"};
existing["abc"] = {Ref:"abc",Title:"tttabc",colour:"yellklow",duck:"sauce"};
existing["xyz"] = {Ref:"xyz",Title:"tttabc",colour:"yellklow",duck:"sauce"};
existing["123"] = {Ref:"123",Title:"ttt123",pet:"cat"};

var newits = {};
newits["abc"] = {Ref:"abc",Title:"tttabc",food:"horse"};
newits["456"] = {Ref:"456",Title:"ttt456",pet:"cat",color:"green",cat:"sauce"};
newits["def"] = {Ref:"def",Title:"tttabc",noise:"moo"};

var itemsAdded = compareHash(existing,newits);
var itemsRemoved =compareHash(newits,existing); 

Now you can check for the existence of "abc" in newits like this:

if (newits.hasOwnProperty('abc')) {
    // do what you need to do
}

To loop through the properties in your object (which is what they’ve become) — and answer your question:

function compareHash(oldObj, newObj) {
    var result = {};
    for (var key in newObj) {
        if (newObj.hasOwnProperty(key)) { // filter in case someone else has added properties to the global Object prototype
            if (!oldObj.hasOwnProperty(key)) {
                result[key] = newObj[key];
            }
        }
    }
    return result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜