简体   繁体   中英

JavaScript - Remove object from array when the condition is met

I have the following array:

  var arr = [{"userId":"12j219","name":"Harry"},{"userId":"232j32", "name":"Nancy"}]

I want to delete a whole object when the following condition is met:

userId == 12j219

For that, I've done the following:

arr.filter((user)=>{
    if(user.userId != "12j219"){
    return user;
    }
    })

It does the job, but for sure it does not delete anything. How can I delete the object from the array?

filter() returns a new array. From the docs:

Return value: A new array with the elements that pass the test.

You need assign the resultant array to arr variable.

Try:

var arr = [{"userId":"12j219","name":"Harry"},{"userId":"232j32", "name":"Nancy"}]
arr = arr.filter((user) => {
    return user.userId !== '12j219'
})

如果在代码的不同位置对同一数组有多个引用,则只需将其分配给自己。

arr = arr.filter(user => user.userId !== "12j219");

Basically array filter iterates on all the elements from array, expects a true or false return. If false that element is removed and if true it stays.

var newArr = arr.filter(function(el){
    return el.userId != "12j219";
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM