Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  112] [ 1]  / answers: 1 / hits: 24435  / 12 Years ago, fri, october 19, 2012, 12:00:00

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.


More From » arrays

 Answers
7

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

[#82474] Wednesday, October 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madalynn

Total Points: 342
Total Questions: 95
Total Answers: 106

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;