1

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!

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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}

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.