What is javascript approach to associative map with objects in the form of keys (not strings, but unique objects)?

I am looking for a javascript method for an associative map / array / hash using objects as keys. Replacing what you can do in ActionScript 3 with flash.utils.Dictionary. I'm sure java and C # have something like this.

It will work just like a regular common object-associated object [key], but instead of string properties you use whole objects in the form of keys (it will correspond not to toString (), like Object, but on a unique instance). It is very convenient to decorate objects that you do not own (using the object as keys and your decorations as a value).

Pseudocode:

decorations[objectA] = [lights, sparkles, ..]; decorations[objectB] = [skulls, spikes, ..]; if(someObject in decorations) updateDecorations(someObject , decorations[someObject]) 

Illustration in javascript and why it does not work on objects:

 // make two objects with same toString() return value var objA = {toString:function(){return 'foo'}}; var objB = {toString:function(){return 'foo'}}; //use objects as keys var assoc = {}; assoc[objA] = 'dataA'; assoc[objB] = 'dataB'; // seperate instances are not equal console.log(objA == objB); // still same data associated: dataB, dataB console.log(assoc[objA]); console.log(assoc[objB]); //with a Dictionary instead of this would be dataA, dataB 

The main problem is that I only need to map the object (it is used by some other process with which you should not interfere, but we still need an association). So no magic .__ hash props or toString () overload (if possible).

Any ideas?

edit: I checked, but it's all toString () or adding magic details

+4
source share
2 answers

I wrote a dictionary class in JS some time ago. This is definitely not ideal as it uses an array to store values โ€‹โ€‹and keys, but works well for small collections.

You will find it here: https://github.com/creynders/creynders-js-lib

+1
source

I did something similar when you link an object (1 of 19 icons) on a map. I extract information from mysql via PHP and bind everything on the map with their X, Y coordinates.

When I add mouse_rollover to all the icons, I just scan the array and find the X, Y coordinates and display a panel with all the other values โ€‹โ€‹imported into multidimensional arrays.

Do you see this help? If so, I can provide some of my code that I used for this. x

0
source

Source: https://habr.com/ru/post/1386749/


All Articles