8

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

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"}
];

通过以上数据,以id为key,我们发现id=2的item有更新的title,id=3的item被删除,id=4的item是新的。

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

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    
    }  
}

这种比较三遍,找到新的、更新的和删除的?

4

3 回答 3

20

没有什么魔法可以做你需要的。您需要遍历这两个对象以查找更改。一个好的建议是将您的结构转换为地图以加快搜索速度。

/**
 * 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);

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

于 2013-02-19T20:28:14.893 回答
3

这是@Juan Mendes答案的打字稿版本

  mapFromArray(array: Array<any>, prop: string): { [index: number]: any } {
    const map = {};
    for (let i = 0; i < array.length; i++) {
      map[array[i][prop]] = array[i];
    }
    return map;
  }

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

  getDelta(o: Array<any>, n: Array<any>, comparator: (a, b) => boolean): { added: Array<any>, deleted: Array<any>, changed: Array<any> } {
    const delta = {
      added: [],
      deleted: [],
      changed: []
    };
    const mapO = this.mapFromArray(o, 'id');
    const mapN = this.mapFromArray(n, 'id');
    for (const 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 (const id in mapN) {
      if (!mapO.hasOwnProperty(id)) {
        delta.added.push(mapN[id]);
      }
    }
    return delta;
  }
于 2017-11-15T16:33:38.103 回答
1

@Juan Mendes与内置地图相同,但效率更高(在查找附加值时)

function mapDelta(oldMap, newMap, compare) {

    var delta = {
        added: [],
        deleted: [],
        changed: []
    };

    var newKeys = new Set(newMap.keys());

    oldMap.forEach(function (oldValue, oldKey) {
        newKeys.delete(oldKey);
        var newValue = newMap.get(oldKey);
        if (newValue == undefined) {
            delta.deleted.push({ key: oldKey, value: oldValue });
            return;
        }
        else if (!compare(oldValue, newValue)) {
            delta.changed.push({ key: oldKey, oldValue: oldValue, newValue: newValue });
        }
    });

    newKeys.forEach(function (newKey) {
        delta.added.push({ key: newKey, value: newMap.get(newKey) });
    });

    return delta;
}

并使用typescript

function mapDelta<K, T>(oldMap: Map<K, T>, newMap: Map<K, T>, compare: (a: T, b: T) => boolean) {

  const delta = {
    added: [] as { key: K, value: T }[],
    deleted: [] as { key: K, value: T }[],
    changed: [] as { key: K, oldValue: T, newValue: T }[]
  };

  const newKeys = new Set(newMap.keys());

  oldMap.forEach((oldValue, oldKey) => {
    newKeys.delete(oldKey);
    const newValue = newMap.get(oldKey);
    if (newValue == undefined) {
      delta.deleted.push({ key: oldKey, value: oldValue });
      return;
    } else if (!compare(oldValue, newValue)) {
      delta.changed.push({ key: oldKey, oldValue: oldValue, newValue: newValue });
    }
  })

  newKeys.forEach((newKey) => {
    delta.added.push({ key: newKey, value: newMap.get(newKey) });
  })

  return delta;
}
于 2020-07-03T12:01:11.497 回答