Explain Codes LogoExplain Codes Logo

Javascript set object key by variable

javascript
dynamic-keys
es6
object-literal
Anton ShumikhinbyAnton Shumikhin·Aug 18, 2024
TLDR

Use JavaScript bracket notation, [], to set an object key by a variable:

let key = "dynamicKey"; let obj = {}; // Watch the magic unravel! obj[key] = "assignedValue"; console.log(obj); // { dynamicKey: 'assignedValue' }

Brackets, here, let key double up as an influencer, setting the trend within obj.

Dynamo: handling dynamic keys

Computed property names: ES6 to the rescue

In the ES6 courtyard, setting up dynamic keys is right down the easy alley:

const key = "dynamicKey"; // Short, sweet, and right on the beat! const obj = {[key]: "newValue"}; console.log(obj); // { dynamicKey: 'newValue' }

ES6 gives you the power to compute a key dynamically within the epicenter of an object literal expression.

Impromptu key-value addition

JavaScript, with its magic wand, allows you to add keys post an object initialization:

let key = "addedLater"; let obj = {}; // Adding strings before they become mainstream obj[key] = "valueAddedAfter"; console.log(obj); // { addedLater: 'valueAddedAfter' }

The array-object duo

Add objects with dynamic keys to an array, easier than ABC in JavaScript:

let array = []; let key = "dynamicKey"; let value = "storedValue"; // Pushing an object into an array - inception! array.push({[key]: value}); console.log(array); // [{ dynamicKey: 'storedValue' }]

A commonly sighted species when dealing with collections of unique objects.

Ensure before assigning

Before you set them, always ensure your dynamic key variables are in a minute's agreement:

let key = getDynamicKey(); // Fetch key value let obj = {}; // Keeping the surprises for birthdays! if (typeof key === "string") { obj[key] = "safeValue"; }

Rise of modern JavaScript

Old vs. New

The journey from the dusty roads of pre-ES6 to the sleek highways of modern syntax offers better readability and easy maintenance:

// Old school var person = {}; person[key] = "John"; // New school let person = {[key]: "John"};

The new syntax not just wins the beauty pageant, but also in the smartness category!

ES6+: Unleashing the features

Unleash the ES6 features like arrow functions, spread/rest operators, and destructuring to simplify and spice up your object thrills:

// The Robin Hoods of dynamic object creation const createObject = (key, value) => ({[key]: value}); // Spread operator to merge objects like butter on bread let object1 = {name: 'John'}; let object2 = {[key]: 'value'}; let mergedObject = {...object1, ...object2}; // Destructuring for easy property tours let {name, [key]: dynamicValue} = mergedObject;

Structural framework: Classes

Classes provide a foundation for building objects with dynamic keys in a structured manner:

class DynamicObject { // The constructors: the new foremen in town constructor(key, value) { this[key] = value; } }

Using a class helps confine the dynamic key assignment into a tight assembly line while adding methods for added marvel.