Explain Codes LogoExplain Codes Logo

How can I add a key/value pair to a JavaScript object?

javascript
object-manipulation
javascript-objects
spread-syntax
Nikita BarsukovbyNikita Barsukov·Oct 1, 2024
TLDR

Leverage dot notation or bracket notation to add a key and its associated value to a JavaScript object:

let obj = {}; obj.newKey = 'newValue'; // Dot notation obj['newKey'] = 'newValue'; // Bracket notation

This promptly adds newKey with newValue to obj. Use dot notation for static keys and bracket notation for dynamic/variable keys.

The art and science of object manipulation

Merging objects: spread syntax vs Object.assign

The spread syntax provides a poetic shorthand for extending objects:

let extendedObj = {...obj, anotherKey: 'anotherValue'}; // Spreading like butter on a warm toast

To play it safe cross-browser, Object.assign is your knight in shining armor:

Object.assign(obj, {anotherKey: 'anotherValue'}); // Conventional, but gets the job done

Precise property control with Object.defineProperty

This is where we get to flex on JavaScript:

Object.defineProperty(obj, 'key', { value: 'controlledValue', writable: true, enumerable: true, configurable: true }); // Check my driving

Deep copying through serialization

Make carbon copies of your objects and add properties like a boss:

let deepCopy = JSON.parse(JSON.stringify(obj)); // Deep as an ocean trench deepCopy.additionalKey = 'additionalValue'; // Just add it!

Performance considerations:

Most times, mutable methods are like sonic, they're faster. But occasionally, in the grand stage of Chrome and Safari, immutable methods reign supreme.

Variable and special property names

Using variables as property names

You can use variables as dynamic property names:

let propName = 'dynamicKey'; // Because we like to move it! obj[propName] = 'dynamicValue'; // Dynamic, like jazz

Special property names

Sometimes, keys can be problematic, like "1st Key":

obj["1st Key"] = 'Special Value'; // Because who said property keys should always make sense?

Compatibility with older browsers and third-party libraries

Using polyfills for Object.assign

For those still having nostalgic moments with older browsers, a polyfill can be useful for Object.assign:

if (typeof Object.assign !== 'function') { // Object.assign polyfill code goes here }

Libraries providing extra utility: Lodash and jQuery

For those specific happy hours, Lodash and jQuery have your back:

  • Lodash:
_.assign(obj, { newKey: 'newValue' }); _.merge(obj, { anotherKey: 'anotherValue' });
  • jQuery:
$.extend(true, obj, { newKey: 'newValue' });

These libraries add a twist handling undefined values. It's best to check their respective user manuals.

Arrays in tuxedos

Consider transforming an object to an array of entries for advanced footwork:

let entries = Object.entries(obj); // Objects in cocktail dresses

Spruce up things and get your object back in shape with Object.fromEntries:

obj = Object.fromEntries(modifiedEntries); // Back to basics