gpt4 book ai didi

javascript只删除循环中数组中的第一个匹配项

转载 作者:行者123 更新时间:2023-11-29 15:39:33 25 4
gpt4 key购买 nike

我有一系列排除项,如下所示:

Exclusions: [ID:"233242", Loc:"West", ID:"322234" , Loc:"South"]

我还在对象中嵌套了一个对象数组,看起来像

Schools : [ O: [ ID:"233242" ] , 1:[ ID:"233242"] , 2: [ID :"954944"] ] 

我需要从学校对象中删除任何具有相同 ID 的匹配数组索引,但仅针对第一个匹配项。这意味着元素 0 应该被删除,但元素 1 应该仍然存在。修复循环的最佳方法是什么:

$.each(Exclusions, function (index, value) {
var loc = value.Loc;
var ID = value.ID;
Object.keys(Schools.District.Pack[loc]).forEach(function (key) {
//i need to scan through the entire object
if (Schools.District.Pack[loc].ID === ID) {
//remove the first match now stop looking
Schools.District.Pack[loc].splice(key, 1);

//break ; incorrect
}
});
});

最佳答案

我会说有另一个用于删除 ID 的查找数组,您将需要这样的东西

var Exclusions = [{ID:"233242", Loc:"West"}, {ID:"322234" , Loc:"South"}];
var Schools = [{ ID:"233242" } ,{ ID:"233242"} , {ID :"954944"} ];

var removedKeys = [];

$.each(Exclusions, function (index, value) {
var loc = value.Loc;
var ID = value.ID;
Object.keys(Schools).forEach(function (key) {
//i need to scan through the entire object
if ((Schools[key].ID === ID) && (removedKeys.indexOf(ID) == -1)) {
removedKeys.push(ID);
//remove the first match now stop looking
delete Schools[key];
}
});
});
console.log(removedKeys);
console.log(Schools);

希望对你有帮助

fiddle

关于javascript只删除循环中数组中的第一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641064/

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