Take the 2-minute tour ×

I search a way to get in Javascript an object which index by reference.

something like:

var myRefMap = new RefMap();

var a = [{}, [], function () {}];

myRefMap.set(a[0], true);
myRefMap.set(a[1], { hello: 'world' });
myRefMap.set(a[2], 42);

myRefMap.has(a[0]); // true
myRefMap.has(a[1]); // true
myRefMap.has(a[2]); // true

myRefMap.has({});             // false
myRefMap.has([]);             // false
myRefMap.has(function () {}); // false

I need this object in order to optimize and avoid an actual heavy array search, during tree browsing within circulars references.


share|improve this question
Do you WANT the last check to actually evaluate to false or are you saying that in your case it does evaluate to false but you would prefer true? –  Waterboy Aug 28 '12 at 17:29
add comment

2 Answers

up vote 0 down vote accepted

One basic way to do this, provided all the stored values are objects would be something like:

(function () {
    var instCount = 0;
    self.RefMap = function () {
        instCount ++;
        var propName = '__RefMap' + instCount + '__';
        this.has = function (o) {
            return propName in o;
        this.set = function (o) {
            o[propName] = true;
        this.remove = function (o) {
            delete o[propName];

//then use it like
var myRefMap = new RefMap();

Edit: Arrays and functions are objects too. And you can use Object.defineProperty to hide the "marking" property, depending on the browsers you target.

share|improve this answer
Thanks, that solve my probleme ! –  nkt Aug 28 '12 at 17:58
add comment

If your code is saying that you want that last condition to evaluate to true, then just using an object and the 'in' directive should work fine.

var mystuff = {};

mystuff[a[0]] = true;
mystuff[a[1]] = {hello:'world'};
mystuff[a[2]] = 42;

(a[0] in mystuff); // true
({} in mystuff);   // true
(a[1] in mystuff); // true
(a[2] in mystuff); // true

If however you wanted ({} in mystuff) to evaluate to false, that's a lot different.

share|improve this answer
add comment

Your Answer


