使用 id 和 Javascript 从数组中删除项目
Remove items from array using id with Javascript
>我有这样的函数: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
您需要
先通过plantId
在source
中找到植物,然后将其从原始数组中删除并推送到目标。打开控制台,它应该记录已删除的植物:
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));
}
}
相关文章:
- 数组删除重复结果Javascript
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- 什么's JavaScript数组中项目的作用域
- 查找数组中项目包含子字符串的索引
- 更新挖空中可观察数组中项目的属性
- 对于数组 {{显示项目}} 中的每个项目
- 字符串替换或通过数组删除
- 按数组中项目的最后一个排序
- 更改数组中项目的颜色,javasccript程序
- js中的对象数组:删除重复项
- KnockoutJS.Mapping.FromJS-可观察数组-删除不起作用
- 循环时更改数组中项目的样式是't工作
- 用于垃圾收集的Javascript数组删除
- 为什么”——数组.删除数组的最后一个元素
- PHP循环通过脚本数组&删除项目
- 我需要在jquery帮助,使数组的项目名称
- 谷歌地图API:试图使用数组删除多个标记
- 我应该在哪里平数组的项目收集骨干
- 如何通过文本搜索返回JSON数组中项目的索引位置?
- 替换数组中项目的实例