比较2个阵列/列表和打印差异

时间:2014-02-17 11:28:01

标签: knockout.js

我总共有4个列表。 storedProceduresInDB1storedProceduresInDB2missingStoredProcedureInDB1missingStoredProcedureInDB2

我想比较storedProceduresInDB1storedProceduresInDB2storedProceduresInDB1storedProceduresInDB2中未包含的项目我想在missingStoredProcedureInDB2添加,反之亦然,因为我只想打印missingStoredProcedureInDB1missingStoredProcedureInDB2中的项目,没有添加,删除等。

就像现在一样,它会将storedProceduresInDB1storedProceduresInDB2中的所有项目添加到两者中 missingStoredProcedureInDB1missingStoredProcedureInDB2

这可能与ko.utils.compareArrays有关,还是有更好的方法呢?

谢谢!

编辑:改进了解释并更新了jsfiddle。

JSFiddle:http://jsfiddle.net/7zp5K/22/

1 个答案:

答案 0 :(得分:3)

举一个使用knockmeout.net utility-functionsdependantObservable比较两个数组的例子,我更新了你的小提琴:http://jsfiddle.net/7zp5K/24/

<强>代码:

比较功能只是记录日志:

self.compare = function () {
   console.log('items missing in database1', self.missingInDb1());
   console.log('items missing in database2', self.missingInDb2());
};

进行两次dependentObservable设置以进行比较:

self.missingInDb1 = ko.dependentObservable(function () {
    var differences = ko.utils.compareArrays(
                     self.storedProceduresInDB2(), self.storedProceduresInDB1());
    //return a flat list of differences
    var results = [];
    ko.utils.arrayForEach(differences, function (difference) {
        if (difference.status === "deleted") {
            results.push(difference.value);
        }
    });        
    return results;
})

self.missingInDb2 = ko.dependentObservable(function () {
    var differences = ko.utils.compareArrays(
                     self.storedProceduresInDB1(), self.storedProceduresInDB2());
    //return a flat list of differences
    var results = [];
    ko.utils.arrayForEach(differences, function (difference) {
        if (difference.status === "deleted") {
            results.push(difference.value);
        }
    });        
    return results;
})