使用 id 和 Javascript 从数组中删除项目

Remove items from array using id with Javascript

本文关键字:数组 删除项目 Javascript id 使用      更新时间:2023-09-26

>我有这样的函数:pickListSelect array具有所有id(数字)来删除source array中的对象,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
您需要

先通过plantIdsource中找到植物,然后将其从原始数组中删除并推送到目标。打开控制台,它应该记录已删除的植物:

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

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

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

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

.splice 上的 MDN

现在在你的实际代码中,你需要检查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 = [];
 }

你可以在这里看看这个小提琴手。我使用下划线.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;
  }

您没有使用匹配的 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));
    }
}