Remove Object from Array using JavaScript

前端 未结 29 2846
南笙
南笙 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:40

    If you want to remove all occurrences of a given object (based on some condition) then use the javascript splice method inside a for the loop.

    Since removing an object would affect the array length, make sure to decrement the counter one step, so that length check remains intact.

    var objArr=[{Name:"Alex", Age:62},
      {Name:"Robert", Age:18},
      {Name:"Prince", Age:28},
      {Name:"Cesar", Age:38},
      {Name:"Sam", Age:42},
      {Name:"David", Age:52}
    ];
    
    for(var i = 0;i < objArr.length; i ++)
    {
      if(objArr[i].Age > 20)
      {
        objArr.splice(i, 1);
        i--;  //re-adjust the counter.
      }
    }
    

    The above code snippet removes all objects with age greater than 20.

提交回复
热议问题