0

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?

1
  • How are you trying to access the attribute properties? Commented Apr 28, 2014 at 17:45

3 Answers 3

2

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"
    };
};
Sign up to request clarification or add additional context in comments.

Comments

1

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';

2 Comments

"You can not give properties/attributes to the values of an array." - of course you can.
What i meant was his array. His array contains strings, thus you can't add properties to them.
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.