Object Operations
By Syncfusion®, Inc. · Last updated
Nested objects and safe reads with ?., destructuring with defaults, copying and combining with spread, collecting leftovers with rest, shallow versus deep copies, computed keys, and immutable updates with const and Object.freeze.
What Are Object Operations?
Object operations = short ways to take values out of an object, or put them into a new one.
- Nested objects and
?.for data inside data. - Destructuring to pull properties into variables.
- Spread
...to copy and combine; rest...to collect what is left. - Computed keys
[name]to build keys from variables.
Simple lesson: you rarely change objects by hand. You read parts out, and build new objects from old ones.
A Real-World Example
An order holds a customer, who holds an address: order.customer.address.city.
When the customer changes the city, the shop makes { ...order, customer: { ...order.customer, city: "Madurai" } }.
The old order stays unchanged, so the page can compare old and new.
order
customer
address city: "Chennai"
order.customer.address.city
Each dot steps one box deeper.
What You Will Learn
- Reading nested objects safely with
?.and??. - Destructuring, renaming and default values.
- Spread to copy and combine; rest to collect the remaining keys.
- Shallow copies versus deep copies (
structuredClone()). - Computed property names.
Nested Objects
Objects inside objects
A nested object is an object stored as a property value of another object.
An order that holds a customer, who holds an address
const order = {
id: 5012,
total: 1840,
customer: {
name: "Asha",
address: {
city: "Chennai",
pincode: "600040",
},
},
};
console.log(order.customer);
Expected output:
{
"name": "Asha",
"address": {
"city": "Chennai",
"pincode": "600040"
}
}
Accessing nested properties
Use one dot per level, read from left to right.
One dot per level
const order = {
id: 5012,
customer: { name: "Asha", address: { city: "Chennai", pincode: "600040" } },
};
console.log(order.customer.name);
console.log(order.customer.address.city);
console.log(order["customer"]["address"]["pincode"]);
Expected output:
Asha
Chennai
600040
If a middle level is missing, the chain breaks with an error:
A missing middle level stops the whole chain
const order = { id: 5013, customer: { name: "Ravi" } };
console.log(order.customer.address.city);
reading 'city' means the value before .city was undefined.
Optional chaining ?. stops safely instead, and ?? gives a fallback:
?. stops safely at a missing level
const order = { id: 5013, customer: { name: "Ravi" } };
console.log(order.customer.address?.city);
console.log(order.customer.address?.city ?? "No address on file");
Expected output:
undefined
No address on file
In Cannot read properties of undefined (reading 'x'), the missing piece is always the one just left of .x.
Destructuring
Destructuring = list the keys in { } on the left of =, and get one variable per key.
Basic destructuring
{ price: cost } takes price but names the variable cost.
Three lines become one
const product = { title: "Desk Lamp", price: 1299, brand: "Lumo" };
const title = product.title;
const price = product.price;
console.log(title, price);
const { brand, price: cost } = product;
console.log(brand, cost);
Expected output:
Desk Lamp 1299
Lumo 1299
Why "destructuring"? It takes a structure apart into separate variables.
Default values
{ currency = "INR" } uses "INR" only when the key is missing or undefined. null is a real value, so it stays.
A default fills in only when the value is undefined
const settings = { theme: "dark", fontSize: undefined, language: null };
const { theme = "light", currency = "INR", fontSize = 16, language = "en" } = settings;
console.log(theme);
console.log(currency);
console.log(fontSize);
console.log(language);
Expected output:
dark
INR
16
null
Defaults do not replace null. Use language ?? "en" when a value might be null.
Spread & Rest
Both use ..., but they do opposite jobs: spread spills properties out; rest gathers them in.
Copying properties
{ ...product } makes a new object with the same properties. Add changes after it.
A copy, and a copy with one change
const product = { title: "Desk Lamp", price: 1299 };
const copy = { ...product };
const onSale = { ...product, price: 999 };
console.log(copy);
console.log(onSale);
console.log(product.price);
console.log(copy === product);
Expected output:
{
"title": "Desk Lamp",
"price": 1299
}
{
"title": "Desk Lamp",
"price": 999
}
1299
false
Combining objects
Spread several objects into one. When a key repeats, the last one wins. So spread defaults first, user choices last.
The last spread wins
const defaults = { theme: "light", fontSize: 16, currency: "INR" };
const userChoices = { theme: "dark", fontSize: 18 };
console.log({ ...defaults, ...userChoices });
console.log({ ...userChoices, ...defaults });
Expected output:
{
"theme": "dark",
"fontSize": 18,
"currency": "INR"
}
{
"theme": "light",
"fontSize": 16,
"currency": "INR"
}
Collecting remaining properties
const { password, ...safeUser } = user takes password out and gathers the rest into safeUser. user itself does not change.
Name the ones you want, collect the rest
const user = { name: "Meera", email: "meera@example.com", password: "s3cret", city: "Kochi" };
const { password, ...safeUser } = user;
console.log(safeUser);
console.log("password" in safeUser);
console.log("password" in user);
Expected output:
{
"name": "Meera",
"email": "meera@example.com",
"city": "Kochi"
}
false
true
Object Copying
const b = a does not copy. Both names point to the same object.
Assignment shares one object between two names
const original = { name: "Kiran", points: 40 };
const sameOne = original;
sameOne.points = 90;
console.log(original.points);
console.log(sameOne === original);
Expected output:
90
true
Shallow copy
Spread makes a new outer object, but nested objects are still shared. That is a shallow copy.
Spread copies the top level and shares everything nested
const order = { id: 5012, status: "packed", customer: { name: "Asha", city: "Chennai" } };
const copy = { ...order };
copy.status = "shipped";
copy.customer.city = "Madurai";
console.log(order.status);
console.log(order.customer.city);
console.log(copy.customer === order.customer);
Expected output:
packed
Madurai
true
A deep copy copies every level. structuredClone() does it:
structuredClone copies every level
const order = { id: 5012, customer: { name: "Asha", city: "Chennai" } };
const deep = structuredClone(order);
deep.customer.city = "Madurai";
console.log(order.customer.city);
console.log(deep.customer.city);
console.log(deep.customer === order.customer);
Expected output:
Chennai
Madurai
false
{ ...obj } is enough for top-level changes. For nested changes, copy that part too ({ ...order, customer: { ...order.customer, city } }), or use structuredClone().
Computed properties
Put a variable or expression in [ ] to use its value as the key: { [field]: "Pune" }.
The key comes from a variable
const field = "city";
const plain = { field: "Pune" };
const computed = { [field]: "Pune" };
console.log(plain);
console.log(computed);
const month = "sep";
const sales = { [month + "Total"]: 48200 };
console.log(sales);
Expected output:
{
"field": "Pune"
}
{
"city": "Pune"
}
{
"sepTotal": 48200
}
Great for counting by category. counts[status] ?? 0 starts each new key at 0:
Counting orders by status with a computed key
const statuses = ["shipped", "pending", "shipped", "cancelled", "shipped"];
let counts = {};
for (const status of statuses) {
counts = { ...counts, [status]: (counts[status] ?? 0) + 1 };
}
console.log(counts);
Expected output:
{
"shipped": 3,
"pending": 1,
"cancelled": 1
}
Immutable Updates
Immutable update = make a new object or array with the change, and leave the original alone. It keeps old versions for "undo", and lets a page see that something changed (old !== new).
- Objects:
{ ...obj, key: value }. Arrays:[...arr, item],filter,map,toSorted(),with(). constonly stops reassignment.Object.freeze(obj)stops changes, but only at the top level.
const versus Object.freeze, and an undo history
const cart = { owner: "Asha", items: [] };
cart.items.push("Notebook");
console.log("const object changed:", cart.items.join(", "));
const order = Object.freeze({ id: 101, status: "pending", address: { city: "Pune" } });
order.status = "shipped";
order.address.city = "Chennai";
console.log("frozen status:", order.status, "| nested city:", order.address.city);
const history = [{ items: [] }];
const add = (item) => history.push({ ...history.at(-1), items: [...history.at(-1).items, item] });
add("Pen");
add("Bag");
history.pop();
console.log("after undo:", history.at(-1).items.join(", "), "| versions kept:", history.length);
Expected output:
const object changed: Notebook
frozen status: pending | nested city: Chennai
after undo: Pen | versions kept: 2
Object Operations on a Web Page
The form builds a new order with spread and a computed key. The old order is never changed, so both can be shown.
Building an updated order with spread
const order = { id: 101, customer: { name: "Asha" }, items: { M: 1 } };
const form = document.querySelector("#order");
const result = document.querySelector("#result");
form.addEventListener("submit", (event) => {
event.preventDefault();
const name = document.querySelector("#customer").value || order.customer.name;
const size = document.querySelector("#size").value;
const qty = Number(document.querySelector("#qty").value);
const updated = {
...order,
customer: { ...order.customer, name },
items: { ...order.items, [size]: (order.items[size] ?? 0) + qty },
};
const { customer: { name: who }, items } = updated;
result.textContent = `${who}: ${JSON.stringify(items)} (old order still ${JSON.stringify(order.items)})`;
console.log("same object?", updated === order, "| shared customer?", updated.customer === order.customer);
});
Pick size L, quantity 2, and press Place order. The new order has L: 2; the old one still has only M: 1.
Easy way to remember: ... on the right of = spreads out (copy). ... on the left of = gathers up (rest).
TL;DR
- Read deep values with dots; guard missing levels with
?.and??. const { a, b: renamed, c = 1 } = objpulls out variables with a rename and a default.{ ...a, ...b }copies and merges; the last key wins.const { x, ...rest } = objcollects the other keys.- Spread is shallow;
structuredClone()is deep.{ [key]: value }builds keys.
Try this
In Combining objects, add const campaign = { theme: "festive" }; and spread it last. theme becomes "festive", and fontSize stays 18.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
customer.address.city with no address | Missing levels give undefined | Use address?.city | Cannot read properties of undefined |
{ language = "en" } when it is null | Defaults replace null | Only undefined | language stays null |
{ ...userChoices, ...defaults } | Order does not matter | The last spread wins | User settings are lost |
| Editing nested data in a spread copy | Spread copies every level | It is shallow | The original changes too |
const copy = original | = copies | = shares | Both change together |
{ field: value } | It uses the variable | Use { [field]: value } | A key named "field" |
Quick reference
| Syntax | Meaning |
|---|---|
order.customer.address.city | read a value several levels down |
order.customer.address?.city | stop with undefined if address is missing |
const { title, price } = product | copy two properties into variables |
const { price: cost } = product | copy price into a variable called cost |
const { currency = "INR" } = settings | use a default when the value is undefined |
{ ...product } | a shallow copy of an object |
{ ...defaults, ...choices } | combine objects, and the later one wins |
const { password, ...rest } = user | collect every other property into rest |
structuredClone(object) | a deep copy of every level |
{ [key]: value } | a computed property whose key comes from an expression |
Exercises
What to Remember
?.keeps nested reads safe.- Destructure to read, spread to copy and merge, rest to leave things out.
- Shallow copies share nested objects.
Next: Collections. Map for lookups with any type of key, and Set for unique values.