Given
var myHash = new Array(); myHash['key1'] = { Name: 'Object 1' }; myHash['key2'] = { Name: 'Object 2' }; myHash['key3'] = { Name: 'Object 3' };
How do I remove key2
, and object 2
from the hash, so that it ends up in a state as if I did:
var myHash = new Array(); myHash['key1'] = { Name: 'Object 1' }; myHash['key3'] = { Name: 'Object 3' };
delete doesn't do what I want;
delete myHash['key2']
simply gives me this:
var myHash = new Array(); myHash['key1'] = { Name: 'Object 1' }; myhash['key2'] = null; myHash['key3'] = { Name: 'Object 3' };
the only docs I can find on splice
and slice
deal with integer indexers, which I don't have.
Edit: I also do not know that 'key2' is necessarily in position [1]
UPDATE
OK slight red herring, delete does seem to do what I want on the surface, however, I'm using json2.js to stringify my object to json for pushing back to the server,
after I've deleted, myHash gets serialized as:
[ { Name: 'Object 1' }, null, { Name: 'Object 3' } ]
Is this a bug in json2.js? or is it something I'm doing wrong with delete?
Thanks
When only a single key is to be removed we can directly use the delete operator specifying the key in an object. Syntax: delete(object_name. key_name); /* or */ delete(object_name[key_name]);
A hash function is a method or function that takes an item's key as an input, assigns a specific index to that key and returns the index whenever the key is looked up. This operation usually returns the same hash for a given key. A good hash function should be efficient to compute and uniformly distribute keys.
There is one simple fix using the library lodash. The _. omit function takes your object and an array of keys that you want to remove and returns a new object with all the properties of the original object except those mentioned in the array.
You're looking for delete
:
delete myhash['key2']
See the Core Javascript Guide
Why do you use new Array();
for hash? You need to use new Object()
instead.
And i think you will get what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With