I'm going to simplify your data structure just a bit, for clarity. I'm also going to assume that the $$hashKey
can be used to determine whether the object to be removed is the same as one in the list -- if that's not the case, and we need to compare all the keys and parameters within the objects, the answer gets quite a bit more complex.
Given those assumptions, here is a vanilla javascript version that should work in all current browsers:
var list = [
{$$hashKey: 1, artist: "Alice"},
{$$hashKey: 42, artist: "Bob"},
{$$hashKey: 25, artist: "Charlie"}
];
var itemToRemove = {$$hashKey: 42, artist: "Bob"};
for (var i=0; i<list.length;i++) {
if (list[i].$$hashKey == itemToRemove.$$hashKey) {
list.splice(i,1); // removes the matched element
i = list.length; // break out of the loop. Not strictly necessary
}
}
console.log(list);
You could simplify that somewhat if itemToRemove
is a reference to an object that is in the list; in that case you can just compare them directly instead of depending on $$hashKey
:
var obj1 = {$$hashKey: 1, artist: "Alice"},
obj2 = {$$hashKey: 42, artist: "Bob"},
obj3 = {$$hashKey: 25, artist: "Charlie"};
var list = [obj1, obj2, obj3];
var itemToRemove = obj2;
for (var i=0; i<list.length;i++) {
if (list[i] === itemToRemove) {
list.splice(i,1); // removes the matched element
i = list.length; // break out of the loop. Not strictly necessary
}
}
console.log(list);
(If you are transpiling from ES6 there are quite a few new convenience methods available so that you don't need to iterate through the array manually: array.prototype.findIndex
, array.prototype.filter
for example, but these are not currently supported in enough browsers to be usable in production. Alternatively, if you are willing to add a library such as underscore.js, you could use _.without()
to remove specific elements.)