Bad algorithm to compare 2 json files

时间:2017-05-16 09:29:43

标签: javascript json

I'm trying to compare two json files in order to detect additions, deletions and modifications. I've got 3 functions for each but I noticed that if my function to detect additions have the second file with less objects than the first, it's bugging. I'm recreating a JSON with all the additions. I don't know how to perfect this algorithm for this case (where there is additions and deletions and it's making a second json file with less objects)

JSON examples :

var tab1 = { "user": [{ "name": "Jhon", "age": "18" }, { "name": "Danny", "age": "20" }, { "name": "Benoit", "age": "20" }] };
var tab2 = { "user": [{ "name": "Ted", "age": "20" }, { "name": "Bernard", "age": "20" }] };

So here is my function :

nb_add is the number of additions, add_1 is the first addition detected

    $scope.detectAdd = function (x, y) {
            if (x !== y) {
                var tmp;
                var nb_add = 0;
                var add_1 = 0;

                for (var i = 0; i < y["user"].length; i++) {
                    if (x["user"][i].name !== y["user"][i].name)
                        nb_add++;
                }

                var i = 0;
                do {
                    if (x["user"][i].name === y["user"][i].name)
                        add_1++;
                    i++;
                }
                while (i <= nb_ajout);

                var tmp = "[{" + '"name":' + '"' + y["user"][ajout_1].name + '",' + '"age":' + '"' + y["user"][ajout_1].age + '"}';
                var i = add_1 + 1;
                if (nb_add > 1) {
                    do {
                        if (x["user"][i].name != y["user"][i].name) {
                            tmp += ",{" + '"name":' + '"' + y["user"][i].name + '",' + '"age":' + '"' + y["user"][i].age + '"}';
                        }
                        i++;
                    }
                    while (i <= nb_add - 1);
                }
                tmp += "]";
                JSON.parse(tmp);
            }

        }

0 个答案:

没有答案