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

时间:2014-02-08 02:13:46

标签: javascript arrays object

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

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

1 个答案:

答案 0 :(得分:1)

我会说为删除的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