Skip to main content
Inspiring
October 3, 2010
Answered

[JS] Adding Methods to Associative Arrays

  • October 3, 2010
  • 1 reply
  • 1017 views

I have an associative array. I would like to add a method to it that will return an array of all the names of the associative array. The problem is it returns the name of the method, too. Is there any for it to only return the names of the properties and not the methods? In the code below I would like myEveryItem item to return an array of two items, not three.

RangePresets = {};

RangePresets.everyItem = getEveryItem;

RangePresets["[Default]"] = new RangePreset(578,800);

RangePresets["Daily Dose"] = new RangePreset(360, 600);

myEveryItem = RangePresets.everyItem();

// RangePreset Constructor

function RangePreset(hr,vr){

     this.horizontalRange = hr;

     this.verticalRange = vr;

}

function getEveryItem(){

     var ei = [];

     for (x in this)

     ei.push(x);

     return ei;

}

This topic has been closed for replies.
Correct answer Harbs.

You can use Object.reflect.properties, but that will give you proto, count, class, and reflect besides your own properties.

You can also test for: if(Object.constructor.name == "Function") to rule out functions.

Harbs

1 reply

Harbs.
Legend
October 4, 2010

Here's one way:

function getEveryItem(){
     var ei = [];
     for (x in this){
        if(x!="getEveryItem"){ei.push(x);}
        return ei;
     }
}

Harbs

Inspiring
October 4, 2010

Well, of course, but that isn't too generic. Is there really no way to differentiate between a method and a property in JavaScript objects?

Harbs.
Harbs.Correct answer
Legend
October 4, 2010

You can use Object.reflect.properties, but that will give you proto, count, class, and reflect besides your own properties.

You can also test for: if(Object.constructor.name == "Function") to rule out functions.

Harbs