admin管理员组文章数量:1400375
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?
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?
Share Improve this question edited May 10, 2017 at 19:29 James 22.4k5 gold badges29 silver badges43 bronze badges asked May 10, 2017 at 19:23 Folky.HFolky.H 1,2044 gold badges16 silver badges40 bronze badges 6- 2 arr = arr.filter(...) – Alex Commented May 10, 2017 at 19:24
-
1
filter
returns a new array. – Evan Trimboli Commented May 10, 2017 at 19:24 - @Alex nice catch ! it solves the issue, thanks ! – Folky.H Commented May 10, 2017 at 19:26
-
1
The filter function should return a boolean, not the user. So it could be simplified to
filteredArray = arr.filter(user => user.userId !== '12j219')
. – Heretic Monkey Commented May 10, 2017 at 19:26 - @MikeMcCaughan totally right, will look clean and simplified, thanks for the suggestion! – Folky.H Commented May 10, 2017 at 19:28
3 Answers
Reset to default 5filter() 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'
})
If you have multiple references to the same array in different places of the code, you can just assign it to itself.
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";
});
本文标签: JavaScriptRemove object from array when the condition is metStack Overflow
版权声明:本文标题:JavaScript - Remove object from array when the condition is met - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744157924a2593195.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论