3

Possible Duplicate:
Javascript expression to define object’s property name?

I'm trying to add objects to an array, but I want to have the name and value to be dynamic. Here's an example:

    (function(){
        var data = [];

        for(i=0; i<5; i++){
            data.push({'name' + i: i});
    }

        console.log(data);
    })()

I guess I can't use a variable for the property so I'm not sure what to do.

3
  • While the answers below are correct, I have to ask WHY are you trying to do this? You'll have to access it in an awkward manner: data[i]['name' + i] to get i... It's nonsensical. Commented Oct 19, 2012 at 17:13
  • @shmiddty This was just a simple example I made so I wasn't confusing anyone with unnecessary details. Commented Oct 19, 2012 at 17:46
  • But, the point remains, if you're pushing the items to an array, data[i]['name' + i] is pointless. Why not just use data[i].name? Commented Oct 19, 2012 at 17:48

3 Answers 3

12

If you want to use a dynamically named property, you need to use array access notation:

var temp = {};
temp['name' + i] = i;
data.push(temp);
In the IIFE:
(function(){
    var data,
        temp,
        i;
    data = [];
    for (i = 0; i < 5; i += 1) {
        temp = {};
        temp['name' + i] = i;
        data.push(temp);
    }
    console.log(data);
}());
Sign up to request clarification or add additional context in comments.

Comments

5

Modified code: key based on variable value can be added in an object using '[]'. jsfiddle

 (function(){
        var data = [], a;

        for(i=0; i<5; i++){
             a = {};
             a['name' + i] = i;
            data.push(a);
    }

        console.log(data);
    })()

Comments

3

Like this:

for(i=0; i<5; i++){
    var obj = {};
    obj["name" + i] = i;
    data.push(obj);
}

But I would wonder why you'd want to hard-code the index into the property name.

Since you have an Array, you already have an associated index. It also makes the property hard to look up.

If you need an association of the original index, I'd use a separate property.

for(i=0; i<5; i++){
    data.push({name: i, idx: i});
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.