-3

我想读取array2并从array1中删除项目并将新项目添加到array1:

如果参数“Removed”是 1,那么我想删除这个项目。如果参数“已移除”为 0,那么我想添加项目。

如何使用 javascript 制作以下解决方案?

我有两个数组:

var array1 = [
{ItemId: "1", Name: "John"},
{ItemId: "2", Name: "George"}, 
{ItemId: "3", Name: "Peter"}
]

var array2 = [
{ItemId: "1", Name: "John", Removed: "1"},
{ItemId: "4", Name: "Mario", Removed: "0"}, 
{ItemId: "5", Name: "Mike", Removed: "0"}
]

我想要以下结果:

var array1 = [
    {ItemId: "2", Name: "George"}, 
    {ItemId: "3", Name: "Peter"},
    {ItemId: "4", Name: "Mario"}, 
    {ItemId: "5", Name: "Mike"}
    ]
4

2 回答 2

2

尝试这个:

注意:这不会对具有相同“名称”或相同“ItemId”的重复条目进行任何检查。您可能也想这样做。

var array1 = [
    {ItemId: "1", Name: "John"},
    {ItemId: "2", Name: "George"}, 
    {ItemId: "3", Name: "Peter"}
];

var array2 = [
    {ItemId: "1", Name: "John", Removed: "1"},
    {ItemId: "4", Name: "Mario", Removed: "0"}, 
    {ItemId: "5", Name: "Mike", Removed: "0"}
];

for(var i = 0; i < array2.length; i++) {
    if(array2[i]["Removed"] == "1") {
        // Remove elements
        for(var j = 0; j < array1.length; j++) {
            if(array1[j]["Name"] == array2[i]["Name"]) {
                array1.splice(j,1);
            }
        }
    } else {
        item = {};
        item["ItemId"] = array2[i]["ItemId"];
        item["Name"] = array2[i]["Name"];
        array1.push(item);
    }
}
于 2013-02-23T16:37:03.797 回答
-1

Object.equals()https://stackoverflow.com/a/1144249/1922787使用:

function mergeArrays(array, operations) {
  var obj;
  var removed;

  for (var i = 0; i < operations.length; i++) {
    obj = operations[i];
    removed = obj.Removed;
    delete obj.Removed;

    if (removed === '0') { array.push(obj); }
    if (removed === '1') { array = removeObjFromArray(array, obj); }
  }

  return array;
}

function removeObjFromArray(array, obj) {
  for (var i = 0; i < array.length; i++) {
    if (obj.equals(array[i])) {
      array.splice(i, 1);
      break; // assuming you don't have dupplicated objects in your array
    }
  }

  return array;
}

array1 = mergeArrays(array1, array2);
于 2013-02-23T16:47:49.513 回答