我试图从数组中创建一个简单的对象。在我的数组中,我有变量存储:

时间:2021-04-30 22:09:28

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"

有没有办法将变量名称指定为对象中的键?例如,我有这些变量存储在数组“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.

我这样做是通过创建一个函数并在数组中运行for循环。现在,我已将密钥分配给索引,我知道这是错误的,但我不知道如何使它成为变量的名称。

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?

1 个解决方案

#1


0  

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

#1


0  

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