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.