简体   繁体   中英

JavaScript Delete an element in an array of objects by property

I have an array of objects in the form of

[  
   {prop1: value1,
   banks:[{_id:value,property2:value2}]
}]

So what I want to do is delete an element in "banks" property by searching for the "_id" value and then remove the found element from the banks array

"_id" property has unique values so there are no multiple occurrences of any value

I am doing this like

$scope.account.banks.splice($scope.account.banks.indexOf(item),1);

is there any better way for doing this?

A better way to do it would be, if possible, to turn the banks array into a Map so you don't need to loop over the array, which may not scale well:

var m = new Map()
for(var bank of account.banks)
  m.set(bank._id, bank)
account.banks = m

Then you can remove items by id directly:

account.banks.delete(id)

Or do it with a regular object even. That way it wouldn't break your Angular code:

var m = {}
for(var bank of account.banks)
  m[bank._id] = bank
account.banks = m

delete account.banks[id]

You could use array.filter to remove the banks that match item . Its a little cleaner than manually looping though it's still a little verbose. I made a little test case to illustrate what I'm talking about.

 var accounts = [{ prop1: 'value1', banks:[{_id:0,property2:'sdfbra'}, {_id:1,property2:'qwedfg'}, {_id:2,property2:'gaasdf'}, {_id:3,property2:'asdfaa'}] }] var item = {_id:1,property2:'qwedfg'}; accounts[0].banks = accounts[0].banks.filter(function(element){ return element._id !== item._id; }); console.log (accounts[0].banks);

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