You can use map() with the splice method to remove objects from the array JavaScript by id. Use the indexOf() method to find the index of the item and then remove it using splice
:
Remove object from array JavaScript by id example
A simple example code removes an object where the id is 2.
<!DOCTYPE html>
<html>
<body>
<script>
var id = 2;
var list =
[{Id: 1,Name: 'a'},
{Id: 2,Name: 'b'},
{Id: 3,Name: 'c'}];
var index = list.map(x => {
return x.Id;
}).indexOf(id);
list.splice(index, 1);
console.log(list);
</script>
</body>
</html>
Output:
Or you can utilize .filter(). The filter
method returns a new instance of the filtered array.
Like this
var id = 2;
var list =
[{Id: 1,Name: 'a'},
{Id: 2,Name: 'b'},
{Id: 3,Name: 'c'}];
var lists = list.filter(x => {
return x.Id != id;
})
console.log(lists);
Or
const array = [
{ id: 1, name: "John" },
{ id: 2, name: "Mary" },
{ id: 3, name: "Peter" }
];
const idToRemove = 2;
const newArray = array.filter(obj => obj.id !== idToRemove);
console.log(newArray);
Remove objects from the array by object property
Used splice
with decrement i
for the next time around, then (and looping backward is also an option):
<script>
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'},
{id:'efg',name:'em'},
{id:'hij',name:'ge'}]
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
i--;
}
}
console.log(arrayOfObjects)
</script>
Output:
Do comment if you have any doubts or suggestions on this JS Array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version