简体   繁体   中英

How to delete an object from array by reference (javascript)?

Simple question, but I cannot find a solution.

I have an array of objects. I also have a reference to an object from this array.

I want to delete the object from the array.

How to do it in Javascript (without comparing object properties)?

PS It is easy to do it in C# (using List collection)

 List<SomeObject> list = ........ ;
 SomeObject element =  ......... ;
 list.Remove(element);

You can use indexOf to get the index of the object and splice to remove it from the array:

var arr = [ { name: 0}, { name : 1 } , {name : 2 } ];
var myObj = arr[1];

arr.splice(arr.indexOf(myObj),1);

console.log(arr);

There is no way to do this with arrays directly. You will have to find or roll your own implementation of an collection which supports similar operation.

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