Home > Back-end >  How do I create an object from two array indexes?
How do I create an object from two array indexes?

Time:10-01

I am trying to create a javascript object with two array indexes, but it does not seem possible. Why is that? For example:

var arr = ["name","john"];
var obj = {arr[0]:arr[1]}

CodePudding user response:

Computed property names need brackets [myPropName]

var arr = ["name","john"]
var obj = {[arr[0]]:arr[1]}

obj.name // 'john'

CodePudding user response:

If you use arr[0] then js will understand that the property name is arr[0] not "name", so you need [arr[0]] for it to interpret as "name" var obj = {[arr[0]]:arr[1]}

CodePudding user response:

You can also do Object.assign,

var arr = ["name","john"];
var obj = {};
var newObj = Object.assign(obj, {[arr[0]]: arr[1]});
console.log(newObj);

  • Related