开发者

Comparing variable size Objects in Javascript

开发者 https://www.devze.com 2023-02-04 01:57 出处:网络
I\'m working on an auto-updating table of informatio开发者_JAVA技巧n using AJAX, but I\'ve run into a bump in the road.I\'m using PHP to return a JSON object on each request, which contains data in th

I'm working on an auto-updating table of informatio开发者_JAVA技巧n using AJAX, but I've run into a bump in the road. I'm using PHP to return a JSON object on each request, which contains data in the following format:

({
    "table": {
        "544532": {
            "field1": "data",
            "field2": "data2",
            "field3": "data3",
            .....
        },
        "544525": {
            "field1": "data",
            "field2": "data2",
            "field3": "data3",
            .....
        },
        ......
    }
}); //

I use Prototype.js to get the list of IDs into an array:

var ids = Object.keys(data.table).sort();

However, random rows of the table could be disappear from the list at any time, and new rows could be added to the end at any time. I assume I would store the array of IDs from the previous request and compare those with the new array, but since random rows can disappear, thus shifting the IDs after that one, how do I compare these so that I can only add new rows or remove deleted rows from the page?


Unfortunately Prototype doesn't include a Set type which would have made things a whole lot simpler. So we'll have to make do with this:

Array.prototype.subtract = function(a){
    return this.reject(this.include.bind(a));
}

The above adds a much needed subtract function. We can use it like this:

added_ids = new_ids.subtract(old_ids);
removed_ids = old_ids.subtract(new_ids);

It's not too slow either since some browsers supports indexOf which Prototype's include checks for and uses.

PS. Array already has an intersect function, if you'd like a complement too here it is...

Array.prototype.complement = function(a){
    return a.reject(this.include.bind(this));
}

Essentially a.subtract(b) is the same as b.complement(a).


Im sure there are better ways to do this - but you will need to store the rows that are shown in the table somewhere - perhaps an array - then loop the JSON object comparing the rows against the array.


You should update your JSON data structure when the table is updated. That would be that data model for the page. Then you can just call Object.keys(data.table) everytime you need it.

0

精彩评论

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