Reputation: 6197
Here is the code and fiddle:
var config = function(){
return {
name: ["john", "lucy", "lily"],
age: ["22", "21", "22"],
gender: ["male", "female", "female"],
people: function(index){
index--;
this.name = name[index];
this.age = age[index];
this.gender = gender[index];
},
people2: function(index){
index--;
this["name"] = name[index];
this["age"] = age[index];
this["gender"] = gender[index];
},
};
}();
alert(config.people(1).name);
alert(config.people2(1).name);
I can get the value by code like:
config.name[1];
I want to restructure a key/value array like:
{name:"john",age:22,gender:male}
The index value delegates the first, second and third people info. Can anyone help me to get the code working? I'm stuck!
Upvotes: 1
Views: 128
Reputation: 458
If you still want to restructure the config object (smashing the arrays)
var config = function(){
return {
name: ["john", "lucy", "lily"],
age: ["22", "21", "22"],
gender: ["male", "female", "female"],
people: function(index){
index--;
this.name = this.name[index];
this.age = this.age[index];
this.gender = this.gender[index];
},
};
}();
config
***Object {name: Array[3], age: Array[3], gender: Array[3], people: function}
config.people(1)
config
***Object {name: "john", age: "22", gender: "male", people: function}
Upvotes: 0
Reputation: 19776
One possibility is, without changing much of your code, as follows:
var config = function(){
var name = ["john", "lucy", "lily"],
age = ["22", "21", "22"],
gender = ["male", "female", "female"];
return {
people: function(index){
return {
name: name[index],
age: age[index],
gender: gender[index]
}
}
};
}();
Upvotes: 2
Reputation: 4147
You can return an object as a result
var config = function() {
return {
name: ["john", "lucy", "lily"],
age: ["22", "21", "22"],
gender: ["male", "female", "female"],
people: function(index) {
index--;
return {
name: this.name[index],
age: this.age[index],
gender: this.gender[index]
};
}
};
}();
alert(config.people(1).name);
Upvotes: 3