简体   繁体   中英

I am trying to write a create a simple object from an array. In my array, I have variable stored:

Is there any way to assign variable names as keys in an object? For example, I have these variables which are stored in the array "stats"

var name = "Sally"
var age = 35
var city = "New York"

var stats = [name, age, city] 

And I want to create an object that uses the variable names as keys and variable values as the objects' values.

example:

var obj = {"name": "Sally", "age": 35, "city": "New York"}

I am doing this by creating a function and running a for loop through the array. Right now, I have key assigned to the index, which I know is wrong, but I don't know how to make it be the variables' names.

function objCreator (array) {
    var obj = {}; 
    for (var i = 0; i < array.length; i++) {
        var key = i;
        var value = array[i];
        obj[key] = value; 
    }
    return obj; 
}

this is what the function returns:

=> { '0': Sally',
  '1': 35,
  '2': 'New York'
 }

Any suggestions?

You need to store the key-names somewhere

var keyNames = ["name", "age", "city"];
function objCreator (array) 
{
    var obj = {}; 
    for (var i = 0; i < array.length; i++) 
    {
      obj[keyNames[i]] = array[i]; //observe change in this line here
    }
    return obj; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM