JavaScript同步两个(对象)数组/查找delta

Fer*_*gal 5 javascript sync

我有两个数组,旧的和新的,在每个位置保存对象.我将如何同步或找到增量(即新数组与旧数组相比新增,更新和删除的内容)

var o = [
    {id:1, title:"title 1", type:"foo"},
    {id:2, title:"title 2", type:"foo"},
    {id:3, title:"title 3", type:"foo"}
];

var n = [
    {id:1, title:"title 1", type:"foo"},
    {id:2, title:"title updated", type:"foo"},
    {id:4, title:"title 4", type:"foo"}
];
Run Code Online (Sandbox Code Playgroud)

使用上述数据,使用id作为键,我们发现id = 2的项目具有更新的标题,id = 3的项目被删除,id = 4的项目是新的.

是否存在具有有用功能的现有库,或者是循环和内循环的情况,比较每一行......例如

for(var i=0, l=o.length; i<l; i++)
{   
    for(var x=0, ln=n.length; x<ln; x++)
    {
        //compare when o[i].id == n[x].id    
    }  
}
Run Code Online (Sandbox Code Playgroud)

做三次这样的比较,找到新的,更新的和删除的?

Jua*_*des 16

做你需要的东西是没有魔力的.您需要遍历两个对象以查找更改.一个很好的建议是将您的结构转换为地图以加快搜索速度.

/**
 * Creates a map out of an array be choosing what property to key by
 * @param {object[]} array Array that will be converted into a map
 * @param {string} prop Name of property to key by
 * @return {object} The mapped array. Example:
 *     mapFromArray([{a:1,b:2}, {a:3,b:4}], 'a')
 *     returns {1: {a:1,b:2}, 3: {a:3,b:4}}
 */
function mapFromArray(array, prop) {
    var map = {};
    for (var i=0; i < array.length; i++) {
        map[ array[i][prop] ] = array[i];
    }
    return map;
}

function isEqual(a, b) {
    return a.title === b.title && a.type === b.type;
}

/**
 * @param {object[]} o old array of objects
 * @param {object[]} n new array of objects
 * @param {object} An object with changes
 */
function getDelta(o, n, comparator)  {
    var delta = {
        added: [],
        deleted: [],
        changed: []
    };
    var mapO = mapFromArray(o, 'id');
    var mapN = mapFromArray(n, 'id');    
    for (var id in mapO) {
        if (!mapN.hasOwnProperty(id)) {
            delta.deleted.push(mapO[id]);
        } else if (!comparator(mapN[id], mapO[id])){
            delta.changed.push(mapN[id]);
        }
    }

    for (var id in mapN) {
        if (!mapO.hasOwnProperty(id)) {
            delta.added.push( mapN[id] )
        }
    }
    return delta;
}

// Call it like
var delta = getDelta(o,n, isEqual);
Run Code Online (Sandbox Code Playgroud)

有关示例,请参见http://jsfiddle.net/wjdZ6/1/