4

我有一个我正在迭代的对象列表。在某些时候,我进行 ajax 调用以将更多对象添加到列表中(可能多次)。

如果其中一个值与现有值匹配,是否有一种有效的方法可以排除任何对象被添加到列表中?

例如:

现有清单

[
  {"value": "1", "id": "123"},
  {"value": "2", "id": "124"},
  {"value": "3", "id": "125"}
]

排除添加第一个对象,因为它的 id 已经在列表中

[
  {"value": "1", "id": "123"},
  {"value": "2", "id": "234"},
  {"value": "3", "id": "235"}
]
4

2 回答 2

5

既然你id是独一无二的,为什么不使用类似map.

  • 您可以创建并保存一个单独的var map = {};
  • 然后每次新对象进来时,您都执行以下操作:map['123'] = true;

更像:

if (!map[new_id])
{
    map[new_id] = true;
    your_array.push({"value": "3", "id": "235"});
}
else
{
    // do what you want... maybe update the value
}

因此,通过这种方式,您不会推送任何具有现有id.

于 2013-08-06T04:00:06.237 回答
1

对象_array_hash引用相同的对象,因此内存开销仅限于数组和散列中的引用,而不是对象的完整副本。

小提琴:http: //jsfiddle.net/vbjWK/

function UniqueArray(array, key) {
    this._array = [];    
    this._hash = {};
    this._key = key;

    this.concat(array);
}

UniqueArray.prototype.concat = function(array) {
    var i, len;

    for (i = 0, len = array.length; i < len; i++) {
        this.push(array[i]);
    }
}

UniqueArray.prototype.push = function(obj) {
    if (!this._hash[obj[this._key]]) {
        this._hash[obj[this._key]] = obj;
        this._array.push(obj);
    }
}

测试:

// Testing testing
var first = [
  {"value": "1", "id": "123"},
  {"value": "2", "id": "124"},
  {"value": "3", "id": "125"}
];

var second = [
  {"value": "1", "id": "123"},
  {"value": "2", "id": "234"},
  {"value": "3", "id": "235"}
]

var ua = new UniqueArray(first, "id");
ua.concat(second);

console.log(ua._array);
于 2013-08-06T06:28:34.813 回答