MichaelKaeser
MichaelKaeser

Reputation: 162

How to access a javascript object's property, when it has a dynamic number as property title?

I have an object which contains a variable number of arrays. The property title always is a number (like here: 15, 117). I could simply access the arrays with names[15] or names[117], but those values are changing constantly because of a data-request.

How can I access them as "the first" or "the second"???

var names = {
    15: Array[1];
    117: Array[1];
};

If this isn't working, I tried a for...in loop to store the arrays in variables, but it didn't really work out:

var name1, name2;

for(var key in names){
    if(name1){name2 = names[key];}
    if(!name1){name1 = names[key];}
}

As soon as there are more arrays, it's overriding name1 with name2 and so on...

Any idea how to solve this? Thanks already for your time.

Upvotes: 0

Views: 93

Answers (3)

gvmani
gvmani

Reputation: 1600

I deleted my earlier answer, as i think is not accurate. js fiddle

var names ={1: ["a","b"],2:["c","d"],3:["e","f"]}

var nameArr=[],i=0; for(var key in names){ nameArr[i++] = names[key]; }

for(i=0;i<nameArr.length;i++)
alert(nameArr[i]);

Upvotes: 1

MichaelKaeser
MichaelKaeser

Reputation: 162

Yes that's absolutely true to access them like this. My problem is, I have to store them separately as variables, to then pass them to a function who could look like this:

var a = name[key];//the first object-property (how to store??)
var b = name[key];//the second object-property (how to store??) 

function doSomething(a,b){
//do something usefull
}

Upvotes: 0

Maxim Zhukov
Maxim Zhukov

Reputation: 10140

There is example, how you can access to properties of your object with loop: http://jsfiddle.net/Y7mHB/

var names = {
    15: '15',
    117: '117'
};

for(var key in names) {
    alert(key + ' ' + names[key]);   
}

Upvotes: 0

Related Questions