gpt4 book ai didi

javascript - 如何通过 id 删除特定对象并将其重新添加到数组中 [jQuery]

转载 作者:行者123 更新时间:2023-11-28 19:59:19 24 4
gpt4 key购买 nike

我在这里问了类似的问题:How to remove and save object from Array

当我只需要检查对象的类型(“组”或“组织”)时,它起作用了,但是我现在需要更具体,并且需要通过 ID 查找对象并将它们删除/重新添加到数组中.

但是,当我尝试调整代码来检查对象的 ID 时,我要么无法找到并删除该 ID,要么最终从数组中删除所有对象。

// re-add Group to networks (This works great)
if (isChecked === 'checked') {

var group_obj = {
'id': name
}

networks.push(group_obj);

// remove Group from networks (Problem exist in the else if)
} else if (isChecked === undefined) {

var group_obj = {
'id': name
}

var removeItem = group_obj;

var obj;
networks = $.grep(networks, function(o,i) {

console.log('removeItem.id = '+removeItem.id);
console.log('name = '+name);

if (removeItem.id === name) {
obj = o;
return true;
}
return false;
}, true);
}

console.log(networks);

控制台
在对复选框采取操作之前,我的网络数组是什么样子的:

[Object, Object, Object]

0: Object
count: 1
id: 6
label: "Who"
type: "Organization"

1: Object
id: 12622

2: Object
id: 13452

当取消选中相应组的复选框时,上面的当前代码将删除数组中的所有对象都被删除,而不仅仅是指定的组对象。

[]

当再次选中该复选框时,所选组将进入数组。

我一开始也尝试过这个:

var obj;
networks = $.grep(networks, function(o,i) {
return o.id === name ? ((obj = o), true) : false;
}, true);

然而,它再次没有找到并删除数组中具有指定 id (name) 的对象,但它使网络数组保持不变。

如何编写 else if 语句来正确删除具有指定 id 的对象并将其余对象保留在数组中?

最佳答案

您应该使用过滤器而不是 grep,如下所示:

networks = networks.filter(function (o,i) {
return o.id !== name ? ((obj = o), true) : false;
});

关于javascript - 如何通过 id 删除特定对象并将其重新添加到数组中 [jQuery],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21940212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com