EN
JavaScript - create object property from variable value
1 answers
0 points
How can I create object property from variable value?
I want to add a new property to myObject
, name it key1
and give it a value of value1
but when I do this it returns undefined
:
xxxxxxxxxx
1
var myObject = new Object();
2
3
var key = 'key1';
4
var value = 'value1';
5
6
myObject.key = value;
7
8
console.log(myObject.key1); // returns 'undefined'
9
console.log(myObject.key); // returns 'value1'
1 answer
0 points
There are two types of property accessors in JavaScript: dot notation and bracket notation.
Use bracket notation to create object property from the variable value:
xxxxxxxxxx
1
myObject[key] = value;
Practical example
xxxxxxxxxx
1
var myObject = {};
2
3
var key = 'key1';
4
var value = 'value1';
5
6
myObject[key] = value;
7
8
console.log(myObject.key1); // value1
9
console.log(myObject['key1']); // value1
Alternative solution (ES6+)
xxxxxxxxxx
1
const key = 'key1';
2
const value = 'value1';
3
4
let myObject = {
5
[key]: value,
6
};
7
8
console.log(myObject.key1); // value1
9
console.log(myObject['key1']); // value1
References
0 commentsShow commentsAdd comment