ben_aaron
ben_aaron

Reputation: 1512

Assign attributes to values in array js/jquery

In my script, a function uses the values in my teststim array.

var teststim =  ["A", "B", "C"]

And I want to give 'attributes' to these values, so that for example A has the attribute "name", B "birthday", ...

I need to find a way to have access to these attributes. I thought about something like this:

var teststim = {content: "A", attribute: "name"}, 
               {content: "B", attribute: "birthday"}, 
               {content: "C", attribute: "whatever"}

Maybe I'm close than I think, but I am not able to access the 'attribute' values corresponding to the content values. What am I missing?

Upvotes: 0

Views: 358

Answers (3)

Metalstorm
Metalstorm

Reputation: 3232

If you want to map a value in the array to another (longer?) value, you can use:

var mapping = {"A" : "name", 
               "B" : "birthday", 
               "C" : "whatever"}


for(var i = 0, len = teststim.length; i < len; i++)
{
    alert(mapping[teststim[i]]);
}

If not, then just have an array of objects:

var teststim = [{ 'content' : "A", 'attribute' : "name" }, 
                { 'content' : "B", 'attribute' : "birthday" }, 
                { 'content' : "C", 'attribute' : "whatever" }];


for(var i = 0, len = teststim.length; i < len; i++)
{
    alert(teststim[i].attribute);
}

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

You need an array of objects:

var teststim = [{content: "A", attribute: "name"}, 
                {content: "B", attribute: "birthday"}, 
                {content: "C", attribute: "whatever"}];

for (var i=0; i<teststim.length; i++) {
    var obj = teststim[i];
    if (obj.content=='C') {
        alert(obj.attribute); // "whatever"
    };
};

Upvotes: 2

Wekker
Wekker

Reputation: 11

You can not give properties/attributes to the values of YOUR array. Therefore, you must start with:

var arr = [
   {content:'A'},
   {content:'B'},
   {content:'C'}
];

Now you can add new attributes, e.g.:

arr[0].attribute = '2';

Upvotes: 1

Related Questions