Creating Dynamic Keys in JavaScript Objects

How can I create a dynamic key to add to a JavaScript object variable?

I’m attempting to do something like this, but my current example doesn’t work:

jsObj = {};

for (var i = 1; i <= 10; i++) { jsObj{‘key’ + i} = 'example ’ + 1; }

What can I do to correctly implement a javascript dynamic object key?

With JavaScript, you can easily create dynamic keys using bracket notation. This method lets you construct each key as a string within your loop.

let jsObj = {};

for (var i = 1; i <= 10; i++) {
    jsObj['key' + i] = 'example ' + i;
}

console.log(jsObj);

Using bracket notation like this ensures your javascript dynamic object key is created accurately in each iteration. It’s straightforward and works well for generating properties on the fly.

You could also use Object.assign() to dynamically add properties to your object. This approach involves creating a temporary object with each dynamic key and value, then merging it into the main object.

let jsObj = {};

for (var i = 1; i <= 10; i++) {
    Object.assign(jsObj, { ['key' + i]: 'example ' + i });
}

console.log(jsObj);

Using Object.assign() is especially helpful if you’re dealing with complex data merges and want to dynamically add to an existing javascript dynamic object key.

If you prefer a reusable method, consider creating a function to add a dynamic key-value pair to your object. This approach centralizes the logic and can be used for any number of additions.

function addDynamicKey(obj, key, value) {
    obj[key] = value;
}

let jsObj = {};

for (var i = 1; i <= 10; i++) {
    addDynamicKey(jsObj, 'key' + i, 'example ' + i);
}

console.log(jsObj);

By defining this function, you can easily maintain and reuse it whenever you need to add a javascript dynamic object key without repeating code.