arrays – how to remove key+value from hash in javascript-ThrowExceptions

Exception or error:

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

How to solve:

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.

###

You say you don’t necessarily know that ‘key2’ is in position [1]. Well, it’s not. Position 1 would be occupied by myHash[1].

You’re abusing JavaScript arrays, which (like functions) allow key/value hashes. Even though JavaScript allows it, it does not give you facilities to deal with it, as a language designed for associative arrays would. JavaScript’s array methods work with the numbered properties only.

The first thing you should do is switch to objects rather than arrays. You don’t have a good reason to use an array here rather than an object, so don’t do it. If you want to use an array, just number the elements and give up on the idea of hashes. The intent of an array is to hold information which can be indexed into numerically.

You can, of course, put a hash (object) into an array if you like.

myhash[1]={"key1","brightOrangeMonkey"};

###

Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.

Leave a Reply

Your email address will not be published. Required fields are marked *