Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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]}
Computed property names need brackets [myPropName]
[myPropName]
var arr = ["name","john"] var obj = {[arr[0]]:arr[1]} obj.name // 'john'
Add a comment
You can also do Object.assign,
Object.assign
var arr = ["name","john"]; var obj = {}; var newObj = Object.assign(obj, {[arr[0]]: arr[1]}); console.log(newObj);
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]}
arr[0]
[arr[0]]
var obj = {[arr[0]]:arr[1]}
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.