Remove Object from Array using JavaScript

前端 未结 29 2051
南笙
南笙 2020-11-22 10:24

How can I remove an object from an array? I wish to remove the object that includes name Kristian from someArray. For example:

som         


        
相关标签:
29条回答
  • 2020-11-22 10:44

    This answer

    for (var i =0; i < someArray.length; i++)
       if (someArray[i].name === "Kristian") {
          someArray.splice(i,1);
       }
    

    is not working for multiple records fulfilling the condition. If you have two such consecutive records, only the first one is removed, and the other one skipped. You have to use:

    for (var i = someArray.length - 1; i>= 0; i--)
       ...
    

    instead .

    0 讨论(0)
  • 2020-11-22 10:44

    Use javascript's splice() function.

    This may help: http://www.w3schools.com/jsref/jsref_splice.asp

    0 讨论(0)
  • 2020-11-22 10:46

    How about this?

    $.each(someArray, function(i){
        if(someArray[i].name === 'Kristian') {
            someArray.splice(i,1);
            return false;
        }
    });
    
    0 讨论(0)
  • 2020-11-22 10:49

    The clean solution would be to use Array.filter:

    var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; }); 
    

    The problem with this is that it does not work on IE < 9. However, you can include code from a Javascript library (e.g. underscore.js) that implements this for any browser.

    0 讨论(0)
  • 2020-11-22 10:49
    someArray = jQuery.grep(someArray , function (value) {
            return value.name != 'Kristian';
    });
    
    0 讨论(0)
  • 2020-11-22 10:49

    You can use map function also.

    someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
    newArray=[];
    someArray.map(function(obj, index){
        if(obj.name !== "Kristian"){
           newArray.push(obj);
        }
    });
    someArray = newArray;
    console.log(someArray);
    
    0 讨论(0)
提交回复
热议问题