使用带有Javascript的id从数组中删除项目

时间:2016-04-26 17:37:23

标签: javascript

我有这样的函数:pickListSelect array包含删除source array中对象的所有ID(数字),target array是推送从source array删除的元素。

    function copy(pickListSelect, source, target) {

         var i, id;

         for (i = 0; i < pickListSelect.length; i++) {
              id = pickListSelect[i];              
              source.splice(id,1);
         }
         pickListSelect = [];
   }

所以我需要从source arra y删除特定对象。我尝试使用该代码但是例如,如果我需要删除id = 5的对象,它只从列表中删除了第5项。

源数组的结构如下:

    [Object, Object, Object, Object, Object, Object, Object, Object, Object]
    0:Object
    plantId:1
    plantName:"Plant 1"

...the rest of others are similar object

4 个答案:

答案 0 :(得分:3)

您需要首先在source plantId中找到工厂,然后将其从原始数组中删除并推送到目标。打开控制台,它应该记录已删除的植物:

var plants = [
    {
        plantId: 1,
        plantName: 'plant 1'
    },
    {
        plantId: 2,
        plantName: 'plant 2'
    },
    {
        plantId: 3,
        plantName: 'plant 3'
    },
    {
        plantId: 4,
        plantName: 'plant 4'
    }
];

function copy(pickListSelect, source, target) {
    var i, id, el;

    for (i = 0; i < pickListSelect.length; i++) {
        id = pickListSelect[i];
        el = findPlant(source, id);
        source.splice(source.indexOf(el), 1);
        target.push(el);
    }
}

function findPlant (arr, id) {
    return arr.filter(function (plant) {
        return plant.plantId == id
    })[0]
}

var test = [];

copy([2,3], plants, test);

console.log(test);

答案 1 :(得分:2)

当你使用.splice时,你需要传入要拼接的起始索引和要拼接的项目数量,试试这个:

source.splice(i,1); // i is your starting index here


array.splice(start, deleteCount[, item1[, item2[, ...]]])

MDN on .splice

现在,在您的实际代码中,您需要使用以上代码检查ID是否匹配,然后拼接:

function copy(pickListSelect, source, target) {

     var i, id;

     for (i = 0; i < pickListSelect.length; i++) {
          if (pickListSelect[i].id === someId) {              
            source.splice(i,1);
          }
     }
     pickListSelect = [];
 }

答案 2 :(得分:1)

您没有查找具有匹配ID的源数组的索引。做这样的事情可能会更好。

var idsToRemove = {};

// build an object of ids to remove (effectively a hashset)
for (var i = 0; i < pickSelectList.length; i++) {
    idsToRemove[pickSelectList[i]] = true;
}

// loop through the source array to find any objects with ids to remove
for (var j = 0; j < source.length; j++) {
    if (source[j].plantId in idsToRemove) {
        target.push(source.splice(j, 1));
    }
}

答案 3 :(得分:1)

你可以看看这个小提琴手here。 我使用underscore.js从源中找到正确的元素并将其移动到目标数组。

var copy = function(pickListSelect, source, target) {
    for (i = 0; i < pickListSelect.length; i++) {
      id = pickListSelect[i];
      var deleteIndex = _.findIndex(source, {Id: id});
            var deletedItem = source.splice(deleteIndex, 1);
            target.push(deletedItem[0])
    }
        pickListSelect = [];
    return target;
  }