JSON Javascript Comparison

I am trying to create a webapp that receives data from a server and shows it to the user. Script receives data from the server every 10 seconds, and if the data has been changed, it warns the user. This is the code I'm using now, but it warns every 10 seconds whether the data has changed or not.

So, how do I need to modify my script to compare it with the old JSON and the new JSON and see if they are different and if they show a warning before updating the data displayed to the user?

$('#ListPage').bind('pageinit', function(event) {
    getList1();
});
setInterval ( "getList1()", 10000 );
var old = "";

function getEmployeeList1() {
    $.getJSON(serviceURL + 'getemployees.php?' + formArray, function(data) {
        if(data != old){ // data from the server is not same as old
            $('#nollalista li').remove();
            keikka = data.key;
            $.each(keikka, function(index, lista) {
                $('#nollalista').append('<li><a href="employeedetails.html?id=' + lista.IND + '">' +
                        '<h4>' + lista.OSO + '</h4>' +
                        '<p>' + lista.AIKA + '</p>' +'</a></li>');
            });
            $('#nollalista').listview('refresh');

            if(old != "")
                alert("New data!");        
            old = data;
        }
    });
}  
0
source share
2 answers

A very simple (but kind of lame) solution compares string representations:

if(JSON.stringify(a) != JSON.stringify(b)) { ... }
+7

10 ,

    if(data != old){ // data from the server is not same as old

true .

json javascript https://github.com/prettycode/Object.identical.js  

    if(!Object.identical(data,old)){ // data from the server is not same as old

:

var a = { x: "a", y: "b" },
b = { x: "a", y: "b" },
c = { y: "b", x: "a" },
d = { x: "Chris", y: "Prettycode.org", developerYears: [1994, 2011] },
e = { y: "Prettycode.org", developerYears: [1994, 2011], x: "Chris" };
f = { y: "Prettycode.org", developerYears: [2011, 1994], x: "Chris" };
console.log(Object.identical(a, b)); // true (same properties and same property values)
console.log(Object.identical(a, c)); // true (object property order does not matter, simple)
console.log(Object.identical(d, e)); // true (object property order does not matter, complex)
console.log(Object.identical(d, f)); // false (arrays are, by definition, ordered)
+1

All Articles