So, I have a javascript array of multiple values:
var keymap = {'name': 'foobaz',
'mappings': [{'id': 1, 'key': 'b'},
{'id': 2, 'key': 'c'},
{'id': 3, 'key': 'd'},
{'id': 1, 'key': 'e'},
{'id': 10, 'key': 'f'},
{'id': 7, 'key': 'g'},
{'id': 1, 'key': 'h'}]
}
I want to remove any entries where key is 'b'. Note the ids correspond to the backend ids. What I want to do is to remove some of the mappings (for example, all with 'id' as '1').
What I've tried is:
for (var i = 0; i < keymap['mappings'].length; i++) {
if (keymap['mappings'][i]['id'] === id_to_match) {
keyboard_map['mappings'].splice(i, 1);
}
}
However, slice will change the indexes of the array in-place, and therefore now i
won't point to the correct index point (as any indexes higher will now be i-n
where n
would be the number of slices done before.
What is the correct way to implement this?
An easy way is to decrement the iterator (this works since you read the length every iteration - so make sure you avoid caching the length)
for (var i = 0; i < keymap['mappings'].length; i++) {
if (keymap['mappings'][i]['id'] === id_to_match) {
keyboard_map['mappings'].splice(i, 1);
i--;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments