I have an array of objects:
var myArr;
Let’s say that on page load it contains 10 objects with the following structure:
{ Id: …, Name: … }
How can I remove an object from myArr
by its Id
?
To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.
To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
You can use the splice() method to remove the item from an array at specific index in JavaScript. The syntax for removing array elements can be given with splice(startIndex, deleteCount) .
Try like this
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);
JSFIDDLE
Or you can utilize .filter()
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);
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With