[英]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"
例如,我有这些变量,它们存储在数组“ 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. 我通过创建一个函数并在数组中运行一个for循环来做到这一点。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.