How can I add a key/value pair to a JavaScript object?
Leverage dot notation or bracket notation to add a key and its associated value to a JavaScript object:
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:
To play it safe cross-browser, Object.assign is your knight in shining armor:
Precise property control with Object.defineProperty
This is where we get to flex on JavaScript:
Deep copying through serialization
Make carbon copies of your objects and add properties like a boss:
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:
Special property names
Sometimes, keys can be problematic, like "1st Key"
:
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
:
Libraries providing extra utility: Lodash and jQuery
For those specific happy hours, Lodash and jQuery have your back:
- Lodash:
- jQuery:
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:
Spruce up things and get your object back in shape with Object.fromEntries
:
Was this article helpful?