user4412054
user4412054

Reputation:

Javascript, retrieve array name

I have this:

var one = ['12','24','36'];

var two = ['10','20','30'];

If I do:

alert(one) I have: 12,24,36. And it's ok.

I need to have the name of the array from another function, where I call it from a for like this:

var test = [one,two]

for (i = 0; i < test.length; i++) {
  alert(test[i]);
}

I have "12,24,36" and then "10,20,30" in the alert, but I need the name of the array, not the content. How to do?

I want two alert with: "one" and "two", the name of Array.

Upvotes: 0

Views: 104

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386660

At some place, the name must be set. While Javascript is can add properties to objects, this can be used for a name property without changing the behaviour of the arrays.

var one = ['12', '24', '36'];
one.name = 'one';
var two = ['10', '20', '30'];
two.name = 'two';
var test = [one, two], i;

for (i in test) {
    document.write(test[i].name + '<br>');
}

Upvotes: 0

Andy
Andy

Reputation: 63550

Use an object to hold your arrays:

var obj = {
    one: ['12','24','36'],
    two: ['10','20','30']
}

for (var p in obj) {
  console.log(p); // log the key
}

Alternatively you can use Object.keys(obj) to retrieve an array of the object keys.

And if you need to log the array contents:

for (var p in obj) {
  console.log(obj[p]); // log the array contents
}

DEMO

Upvotes: 3

elad.chen
elad.chen

Reputation: 2425

You can use an "Object Literal" and use the property name as the name, and the value as the array..

For example:

var arrays = {
"one": [1,2,3],
"two": [1,2,3]
}

for ( var k in arrays ) {
  alert('"Array name" = ' + k)
  alert('"Array value" = ' + arrays[k].toString() )
}

Upvotes: 0

Prabhjyot Singh
Prabhjyot Singh

Reputation: 1

Yes, I agree with elad.chen. You can try something like:

var objects = [
    {name:"one",value:['12','24','36']},
    {name:"two",value:['12','24','36']}
];

for(var i=0;i<objects.length;i++){
    console.log(objects[i].name); 
    console.log(objects[i].value); 
}

Upvotes: 0

Related Questions