Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Set A JS object property name from a variable

Tags:

javascript

People also ask

How do you change the property of an object JavaScript?

To change the value of an existing property of an object, specify the object name followed by: a dot, the name of the property you wish to change, an equals sign, and the new value you wish to assign.

Can we assign object to a variable in JS?

Object.assign() Method Among the Object constructor methods, there is a method Object. assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.

How do you declare a property in JavaScript?

To add a new property to a Javascript object, define the object name followed by the dot, the name of a new property, an equals sign and the value for the new property.


var jsonVariable = {};
for(var i=1; i < 3; i++) {
  jsonVariable[i + 'name'] = 'name' + i;        
}

You'll have to use [] notation to set keys dynamically.

var jsonVariable = {};
for(i=1; i<3; i++) {        
 var jsonKey  = i+'name';
 jsonVariable[jsonKey] = 'name1';

}

Now in ES6 you can use object literal syntax to create object keys dynamically, just wrap the variable in []

var key  = i + 'name';
data = {
    [key] : 'name1',
}

With ECMAScript 6, you can use variable property names with the object literal syntax, like this:

var keyName = 'myKey';
var obj = {
              [keyName]: 1
          };
obj.myKey;//1

This syntax is available in the following newer browsers:

Edge 12+ (No IE support), FF34+, Chrome 44+, Opera 31+, Safari 7.1+

(https://kangax.github.io/compat-table/es6/)

You can add support to older browsers by using a transpiler such as babel. It is easy to transpile an entire project if you are using a module bundler such as rollup or webpack.


Use a variable as an object key

let key = 'myKey';

let data = {[key] : 'name1'; }

See How to iterete on your object here


This is the way to dynamically set the value

var jsonVariable = {};
for (var i = 1; i < 3; i++) {
    var jsonKey = i + 'name';
    jsonVariable[jsonKey] = 'name' + i;
}