0

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?

7
  • 1
    Does indexOf on item actually work? Commented Sep 25, 2015 at 13:15
  • Should be moved to Code Review Commented Sep 25, 2015 at 13:15
  • item is an object with the all the same properties as an object in banks array would have. But, I am not getting the right results that's why I posted on SO Commented Sep 25, 2015 at 13:18
  • 1
    Your 'accounts' array isn't a valid array. Is it actually an array of objects, each with prop1 and banks as members? Commented Sep 25, 2015 at 13:28
  • 1
    No, it is not. I am using this on client side so it is on angularjs and not in server side Commented Sep 25, 2015 at 14:11

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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]

1 Comment

This is probably way more efficient. Especially if you're accessing banks by _id all the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.