To update a dictionary (object) in JavaScript, you assign a value to a key: obj.key = value or obj["key"] = value. For adding multiple keys at once, use Object.assign(obj, newData), and for a newer, safer approach that creates a new object, use the spread operator: const updated = {...obj, ...newData}.
What “Dictionary” Means in JavaScript
JavaScript doesn’t have a dedicated “dictionary” type like Python or C#. Instead, developers use plain objects ({}) or the Map class. Plain objects are the most common choice for simple key-value storage because they are literal, easy to read, and work with JSON. Maps, introduced in ES6, offer better performance for frequent additions/deletions and allow non-string keys (like numbers or objects), but they lack the convenient dot notation. When someone says “update dictionary” in a JavaScript context, they almost always mean updating a plain object.
Direct Assignment: The Basic Way
You can update an existing key or add a new one with the same syntax. If the key exists, its value is overwritten; if not, the key is created.
obj.name = "Alice"— dot notation, works for keys that are valid identifiers.obj["first name"] = "Bob"— bracket notation, required for keys with spaces, hyphens, or starting with a digit.obj[someVariable] = value— bracket notation with a variable holding the key name.
Example:
let user = { id: 1, age: 30 };
user.age = 31; // update existing
user.city = "Paris"; // add new
console.log(user); // { id: 1, age: 31, city: "Paris" }
This is the fastest and most readable method for a single key. Use it unless you need to merge many properties at once.
Object.assign: Merge Multiple Keys
When you have a source object (or several) whose properties you want to copy into the target, Object.assign(target, ...sources) updates the target in place and returns it. It overwrites existing keys and adds missing ones.
let settings = { theme: "dark", volume: 70 };
let newPrefs = { volume: 80, notifications: true };
Object.assign(settings, newPrefs);
console.log(settings); // { theme: "dark", volume: 80, notifications: true }
Note: Object.assign performs a shallow merge. If a property value is itself an object (e.g., settings.colors), it copies the reference, not a deep copy. So mutating the nested object in the source also mutates the target. For deep merging, you need a recursive function or a library like Lodash’s merge.
Spread Operator: Immutable Update
Instead of mutating the original object, you can create a new object that includes the old properties plus the updates. This is a common pattern in React and functional programming because it avoids side effects.
let original = { a: 1, b: 2 };
let updated = { ...original, b: 3, c: 4 };
console.log(original); // { a: 1, b: 2 } (unchanged)
console.log(updated); // { a: 1, b: 3, c: 4 }
The spread operator (...) copies all enumerable own properties. Order matters: later spreads override earlier ones. So {...original, b: 3} gives b a new value, while {b: 3, ...original} would keep original.b. This is an immutable update — you don’t touch the original. It’s slightly slower than Object.assign for large objects, but the clarity and safety usually win.
Updating Nested Objects and Arrays
Updating a nested property requires care because the assignment only changes the leaf value, but the parent object reference stays the same. For example:
let config = { server: { host: "localhost", port: 8080 } };
config.server.port = 9090; // works fine
But if you want an immutable update of a nested field, you must copy each level:
let newConfig = { ...config, server: { ...config.server, port: 9090 } };
This is verbose but explicit. For arrays inside objects, use map or spread to replace elements. For example, to update the second item in config.tags:
let newTags = config.tags.map((t, i) => i === 1 ? "new" : t);
let newConfig2 = { ...config, tags: newTags };
A common mistake is to do config.tags[1] = "new" and then expect the original to remain unchanged — it doesn’t, because arrays are objects too.
Map vs Object: Which to Update?
If you need frequent updates, key order preservation, or non-string keys, Map is often better. Updating a Map uses its own methods:
map.set(key, value)— adds or updates a key.map.delete(key)— removes a key.map.has(key)— checks existence.
Example:
let m = new Map([["a", 1]]);
m.set("a", 2); // update
m.set("b", 3); // add
console.log(m.get("a")); // 2
Maps also have a size property (objects don’t). However, Maps are not serializable to JSON directly — you must convert with Array.from(m) or Object.fromEntries(m). For most simple dictionaries, plain objects are fine and more familiar.
Common Pitfalls and Gotchas
Several issues trip up developers when updating objects:
- Prototype pollution: Avoid using
__proto__as a key. Assigning to it can change the object’s prototype and cause unexpected behavior. UseObject.create(null)for a truly empty dictionary. - Undefined values: Setting a key to
undefinedstill creates the key. To remove a key, usedelete obj.key. - Copying references: As mentioned, shallow copies share nested objects. If you update a nested object in the copy, the original changes too.
- Key order: Integer-like keys (e.g.,
"1","2") are iterated first in ascending order, then string keys in insertion order. This can surprise you when usingfor...in. - Freezing: If an object is
Object.freeze()d, assignments silently fail in non-strict mode or throw in strict mode. Check withObject.isFrozen().
Performance and When It Matters
For most applications, updating a dictionary is instantaneous. But if you’re doing thousands of updates per second (e.g., in a game loop or real-time data processing), consider:
- Using
Mapinstead of object — V8 optimizes Map operations well. - Avoiding
Object.assignwith many sources — it creates intermediate objects. - Preferring direct assignment over spread if you don’t need immutability.
Benchmarks vary by engine, but in general, direct property assignment is fastest. The spread operator is slower because it allocates a new object. For a single update, don’t overthink it; for batch updates, measure.
Frequently Asked Questions
How do I update a dictionary key only if it exists?
Check first with if ("key" in obj) or if (obj.hasOwnProperty("key")), then assign. But if you want a default value when missing, use obj.key = obj.key ?? defaultValue — this updates only if the current value is null or undefined.
What’s the difference between Object.assign and the spread operator?
Both copy properties, but Object.assign mutates the target object and returns it, while spread creates a new object. Also, spread only copies enumerable own properties, same as Object.assign. For merging two objects into a new one, spread is more concise.
How do I update a dictionary without mutating the original?
Use the spread operator: const newObj = {...oldObj, key: newValue}. Or use Object.assign({}, oldObj, {key: newValue}). Both create a shallow copy. For deep immutability, you need a library or a recursive clone.
Can I use a variable as the key name?
Yes, use bracket notation: obj[myVar] = value. Dot notation does not accept variables. This works for both reading and writing.
Why does my update not work when the object is frozen?Object.freeze() makes the object non-extensible and all properties non-writable. Assignments will fail silently in non-strict mode or throw a TypeError in strict mode. To update, you must create a new object instead.
Is there a way to update multiple keys conditionally?
Loop through an array of keys and check conditions, or build a new object with a conditional spread: {...(condition && {key: value})}. This adds the key only if the condition is truthy.
Related
- Makita TD020DSEW Impact Driver Kit: Full Review
- Select a Certificate Spotify: What It Means & How to Do It
- Google Sheets COUNTIF: Count Cells That Match
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Microsoft Excel Project Timeline Template: How to Build OneA Microsoft Excel project timeline template is a worksheet that lays out tasks against calendar dates, often using…
- Excel Data Validation Custom Lists: Setup and TipsIn Excel for Microsoft 365 on Windows, a data validation custom list is a dropdown menu that limits…
- Excel Shortcut to Expand a Column: AutoFit and MoreIn Excel for Microsoft 365 on Windows, select a cell in the column and press Alt, H, O,…
- Edit a Data Validation List in Excel: Steps and FixesTo edit a data validation list in Microsoft Excel for Microsoft 365 on Windows, select a cell that…
- Excel Linear Equation Solver for y = mx + b: A GuideTo calculate a value from y = mx + b in Excel, put the slope m, the intercept…
- Can You Password Protect One Sheet in Excel? Here’s HowYes. In Excel for Microsoft 365 on Windows, select the worksheet, choose Review > Protect Sheet, enter an…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.