gpt4 book ai didi

javascript - 如果值匹配,如何从数组中删除元素?

转载 作者:行者123 更新时间:2023-11-30 16:13:21 25 4
gpt4 key购买 nike

如果我在对象中找到值,我想从数组中删除这些值。

完成此任务的最佳解决方案是什么?

控制键

  var selectedOwners = [];
$scope.deleteOwner = function(dataItem){
var workerKey;
var fullName;
angular.forEach(selectedOwners,function(val,index){
workerKey = val.workerKey;
fullName = val.fullName;
})
if(dataItem.workeyKey === workerKey || dataItem.fullName === fullName){
selectedOwners.splice(workerKey,fullName);
}
}

数组和对象

Array  selectedOwners = [{"fullName":"Johnson, Rocio","workerKey":3506},{"fullName":"Johnson, John S.","workerKey":571},{"fullName":"Johnson, Camille A.","workerKey":1368}]

Object {
"workerKey": 3506,
"fullName": "Johnson, Rocio",
}

最佳答案

应该像这样简单:

var selectedOwners = [{
"fullName": "Johnson, Rocio",
"workerKey": 3506
}, {
"fullName": "Johnson, John S.",
"workerKey": 571
}, {
"fullName": "Johnson, Camille A.",
"workerKey": 1368
}];

var obj = {
"workerKey": 3506,
"fullName": "Johnson, Rocio",
};


for (var i = 0; i < selectedOwners.length; i++) {
if (selectedOwners[i].workerKey === obj.workerKey) {
selectedOwners.splice(i, 1);
break;
}
}

请记住,for 循环假定 workerKey 在数组中是唯一的。这就是为什么我们只需要比较 workerKey 属性,并且在找到匹配项后我们也会跳出 for 循环。

如果 workerKey 不唯一,则循环如下:

for (var i = 0; i < selectedOwners.length; i++) {
if (selectedOwners[i].workerKey === obj.workerKey &&
selectedOwners[i].fullName === obj.fullName) {
selectedOwners.splice(i, 1);

// we need to decrement i by one because
// we just removed an element from the array
i--;
}
}

关于javascript - 如果值匹配,如何从数组中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35897777/

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