...

View Full Version : How do I get the members of an arbitrary object?

hotwheelharry
10-12-2008, 07:51 AM
so basically, how do I write a function that does this.

function getMembers(obj)
{
var extractedMembers = new Array();
for(member in obj)
{
extractedMembers.push(member);
}
return extractedMembers;
}

It extracts the members in any arbitrary object and returns them in an array.

Many thanks!

rnd me
10-12-2008, 03:20 PM
three handy functions for raking objects:

obVals : an array of the object's values (variants)
obKeys : an array of the object's keys (strings)
obMap : an array of the object's keys and values: [key,value] (arrays)

function obVals(ob) {var r = [];var i = 0;for (var z in ob) {if (ob && ob.hasOwnProperty && ob.hasOwnProperty(z)) {r[i++] = ob[z];}}return r;}
function obKeys(ob) {var r = [];var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {r[i++] = z;}}return r;}
function obMap(ob) {var r = [];var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {r[i++] = [z, ob[z]];}}return r;}

//same code expanded
function obVals(ob) {
var r = [];
var i = 0;
for (var z in ob) {
if (ob && ob.hasOwnProperty && ob.hasOwnProperty(z)) {
r[i++] = ob[z];
}
}
return r;
}

function obKeys(ob) {
var r = [];
var i = 0;
for (var z in ob) {
if (ob.hasOwnProperty(z)) {
r[i++] = z;
}
}
return r;
}

function obMap(ob) {
var r = [];
var i = 0;
for (var z in ob) {
if (ob.hasOwnProperty(z)) {
r[i++] = [z, ob[z]];
}
}
return r;
}

//examples

var ob = ({ a:1,b:2,c:3 });

hotwheelharry
10-12-2008, 07:42 PM
WOW!
Thank you so much, that's exactly what I was looking for!