Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove key+value from hash in javascript

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

like image 489
Andrew Bullock Avatar asked Sep 06 '09 15:09

Andrew Bullock


People also ask

How do you remove a key value pair from an object in typescript?

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]);

What is hash key in JavaScript?

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.

How do I delete multiple object 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.


2 Answers

You're looking for delete:

delete myhash['key2'] 

See the Core Javascript Guide

like image 79
karim79 Avatar answered Sep 20 '22 18:09

karim79


Why do you use new Array(); for hash? You need to use new Object() instead.

And i think you will get what you want.

like image 39
Eldar Djafarov Avatar answered Sep 19 '22 18:09

Eldar Djafarov