I have an array of objects where the key is an md5 string and the value is an object
[0315778255cca8d2f773642ad1d3678f] = {a:12,b:34}. I need to remove array elements based on their key, i tried splice but failed cause i suppose the keys are non numeric.
I also tried to splice by position, but that failed to, and even delete the element but we all know that it is not ideal.
I could change my implemantation from array to object but that too will have the same problems more or less i suppose.
Any ideas are welcome
spliceis indeed about the array indexes (as the numeric properties of arrays are called), not about other properties.To remove a property from an object (including an array), use
delete:Despite its similarity to “delete” in other languages,
deletein JavaScript has nothing (directly) to do with memory management; all it does is remove a property from an object (entirely; it doesn’t just set the property’s value toundefinedor something).Side note: If you’re only using non-numeric properties, you probably don’t want an array at all. The only reason for using JavaScript’s
Arraytype is if you need the special handling it gives properties whose names are all digits, the magiclength(which only relates to the numeric properties), and the stuff fromArray.prototype— none of which does anything with other, non-index properties.Re your comment below:
No,
deleteremoves the property, entirely. It does not leaveundefinedin its place. You might be thinking it does because any time you try to retrieve a property from an object that doesn’t exist, you get backundefined. E.g.:You can prove that the property really is removed by using
hasOwnPropertyorin:inwill check the object and its prototype chain;hasOwnPropertyjust checks the object itself.Coming back to
delete:Live example | source
Note that both
delete obj.foo;anddelete obj['foo'];work iffoois a valid identifier. But for properties whose names aren’t valid identifiers (like your md5 sums), you have to use the bracketed form with the string as I showed above (delete theArray['0315778255cca8d2f773642ad1d3678f'];).