从数组对象Jquery中删除对象

时间:2014-07-24 09:42:25

标签: javascript jquery

我正在创建如下的数组对象:

var numberOfSameDeficiency = [];
 for (var i = 0; i < result.length; i++) {

                    var deficiencyId = result[i].Deficiency_Id;
                    var deficiencyName = result[i].DeficiencyName;

                    //check to see if this deficiency is already in the list of available selections
                    if ($("#drpDeficiency option[value='" + deficiencyId + "']").length == 0) {
                        var option = $('<option>');
                        option.attr('value', deficiencyId);
                        option.text(deficiencyName);

                        $select.append(option);
                    }
                    else {
                        Tests = {};
                        Tests.TestId = testId;
                        Tests.DeficiencyId = deficiencyId;
                        numberOfSameDeficiency.push(Tests);
                    }
                }

我想删除不同函数上的对象:

for (var i = 0; i < result.length; i++) {
                console.log(numberOfSameDeficiency);
                var isFound = false;
                var deficiencyId = result[i].Deficiency_Id;

                if (numberOfSameDeficiency) {

                    numberOfSameDeficiency.forEach(function (entry) {
                       if (entry.DeficiencyId != deficiencyId) {
                           isFound = true;
                        **numberOfSameDeficiency.splice(entry, 1); // Generating Error (Remove all items from array object)** 
                           return;
                       }

                    });
                    // console.log("end if");
                }
                if (!isFound) {
                    $("#drpDeficiency option[value='" + deficiencyId + "']").remove();
                }

            }

那么应该使用什么行代码从数组对象中删除特定对象。

2 个答案:

答案 0 :(得分:1)

试试这个

for( i=myArray.length-1; i>=0; i--) {
    if( myArray[i].field == "money") myArray.splice(i,1);
}

这也有效

myArray = [{name:"Alpesh", lines:"2,5,10"},
             {name:"Krunal", lines:"1,19,26,96"},
             {name:"Deep",lines:"3,9,62,36" }]
johnRemovedArray = myArray
               .filter(function (el) {
                        return el.name !== "Krunal";
                       });

答案 1 :(得分:0)

创建此原型函数:

Array.prototype.removeElement = function (el) {
    for(let i in this){
        if(this.hasOwnProperty(i))
            if(this[i] === el)
                this.splice(i, 1);
    }
}

然后致电:

let myArray = ['a','b','c','d'];
myArray.removeElement("c");

它也适用于对象:

let myObj1 = {name: "Mike"},
    myObj2 = {name: "Jenny"},
    myArray = [myObj1, myObj2];

myArray.removeElement(myObj2);