Day 7: Objects, Destructuring, Spread & JSON
✅ Today you will learn
- Model real things with key: value pairs
- Dot vs bracket access, add/update/delete properties
- Methods and a first look at this
- Object.keys / values / entries, destructuring, spread
- Arrays of objects and JSON – the language of APIs
🏢 In the real world
A product is not one value – it has a name, a price, a category, stock and a rating. An order has a customer, items and a total. Real apps (and every API on the internet) represent data as objects and arrays of objects. After today you can read any JSON response a backend developer sends you.
Creating and reading objects
const product = {
id: 1,
name: 'Kaju Katli',
price: 900,
category: 'dry',
inStock: true,
'shelf life': '15 days', // keys with spaces need quotes
};
console.log(product.name, product.price); // dot access
console.log(product['shelf life']); // bracket access
const field = 'category';
console.log(product[field]); // dynamic key → brackets
console.log(product.discount); // missing → undefinedAdd, update, delete, check
const order = { id: 1042, customer: 'Aarti', total: 1800 };
order.status = 'packing'; // add
order.total = 1890; // update
delete order.customer; // delete
console.log(order);
console.log('status' in order, Object.hasOwn(order, 'customer'));
const settings = Object.freeze({ gst: 5 }); // lock an object
settings.gst = 18; // silently ignored (error in strict mode)
console.log(settings.gst);Methods and this
const cartLine = {
name: 'Ghewar',
price: 650,
qty: 2,
total() { // a method = function inside an object
return this.price * this.qty; // this = the object the method was called on
},
label() {
return `${this.qty} × ${this.name} = ₹${this.total()}`;
},
};
console.log(cartLine.total());
console.log(cartLine.label());Do not write total: () => this.price * this.qty. Arrow functions have no own this, so this.price is undefined. Use the method shorthand total() { … }. Day 17 explains this fully.
Looping over objects
const stock = { kaju: 25, ghewar: 8, rasmalai: 12, kalakand: 0 };
console.log(Object.keys(stock));
console.log(Object.values(stock));
for (const [item, kg] of Object.entries(stock)) {
console.log(`${item.padEnd(9)} ${kg > 0 ? kg + ' kg' : 'OUT OF STOCK'}`);
}
const totalKg = Object.values(stock).reduce((sum, kg) => sum + kg, 0);
console.log('Total stock:', totalKg, 'kg');Destructuring and spread
const customer = { name: 'Riya', phone: '9829012345', address: { city: 'Jaipur', pin: '302003' } };
const { name, phone } = customer; // pull out properties
const { address: { city } } = customer; // nested
const { email = 'not given' } = customer; // default value
console.log(name, phone, city, email);
const [firstSweet, , thirdSweet] = ['Kaju', 'Ghewar', 'Ladoo']; // array destructuring
console.log(firstSweet, thirdSweet);
const updated = { ...customer, phone: '9876543210' }; // copy + override
console.log(customer.phone, '→', updated.phone);
function printLabel({ name, address: { pin } }) { // destructure parameters
return `${name} – PIN ${pin}`;
}
console.log(printLabel(customer));{ ...customer } copies the top level only; updated.address is still the same object as customer.address. Use structuredClone(customer) for a full deep copy.
Arrays of objects – real data
const orders = [
{ id: 1041, customer: 'Aarti', city: 'Jaipur', total: 1800, paid: true },
{ id: 1042, customer: 'Rahul', city: 'Ajmer', total: 650, paid: false },
{ id: 1043, customer: 'Sana', city: 'Jaipur', total: 2400, paid: true },
];
let revenue = 0, unpaid = [];
for (const o of orders) {
if (o.paid) revenue += o.total;
else unpaid.push(o.customer);
}
console.log('Revenue collected: ₹' + revenue);
console.log('Remind:', unpaid.join(', '));
console.table(orders.map(({ id, customer, total }) => ({ id, customer, total })));JSON – how data travels
const order = { id: 1043, items: [{ name: 'Rasmalai', qty: 2 }], paid: true };
const text = JSON.stringify(order); // object → JSON string (to send/save)
console.log(text, typeof text);
const back = JSON.parse(text); // JSON string → object (received)
console.log(back.items[0].name, typeof back);
console.log(JSON.stringify(order, null, 2)); // pretty print with 2 spaces| JSON rule | Example |
|---|---|
| Keys always in double quotes | {"name": "Ghewar"} |
| Strings in double quotes only | "Jaipur" (not 'Jaipur') |
| Allowed values | string, number, true/false, null, object, array |
| Not allowed | functions, undefined, comments, trailing commas |
| Dates | Stored as strings: "2026-10-25T10:30:00Z" |
Real task: a product card from an object
<div id="card"></div>
<script>
const product = { name: 'Malai Ghewar', price: 650, unit: 'kg', rating: 4.7, stock: 8, image: 'images/ghewar-400.webp' };
function productCard({ name, price, unit, rating, stock, image }) {
const stockText = stock === 0 ? '❌ Out of stock' : stock < 10 ? `⚠️ Only ${stock} left` : '✅ In stock';
return `
<article style="width:220px;border:1px solid #eee;border-radius:12px;overflow:hidden">
<img src="${image}" alt="${name}" style="width:100%;display:block">
<div style="padding:10px">
<b>${name}</b> <small>★ ${rating}</small><br>
₹${price}/${unit}<br><small>${stockText}</small>
</div>
</article>`;
}
document.querySelector('#card').innerHTML = productCard(product);
</script>🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
Show solution
const student = {
name: 'Riya', roll: 12,
marks: { maths: 88, science: 92, english: 73 },
average() {
const values = Object.values(this.marks);
let sum = 0;
for (const m of values) sum += m;
return Math.round(sum / values.length * 10) / 10;
},
};
console.log(`${student.name} (Roll ${student.roll}): ${student.average()}`);{"orderId":"SS1","items":[{"name":"Ladoo","qty":2,"price":500},{"name":"Kaju Katli","qty":1,"price":900}]}Show solution
const json = '{"orderId":"SS1","items":[{"name":"Ladoo","qty":2,"price":500},{"name":"Kaju Katli","qty":1,"price":900}]}';
const order = JSON.parse(json);
let total = 0;
for (const { name, qty, price } of order.items) {
console.log(`${name}: ${qty} × ₹${price} = ₹${qty * price}`);
total += qty * price;
}
console.log(`${order.orderId} total ₹${total}`);Quick quiz
🧠 Quick Quiz – test yourself
Interview corner
💼 Interview Corner
How do you deep-copy an object?
structuredClone(obj) (modern, handles dates, maps, nested objects); JSON.parse(JSON.stringify(obj)) works only for plain JSON-safe data and loses functions, undefined and dates. Spread/Object.assign are shallow.
What is destructuring and why is it useful?
Syntax to unpack properties or array items into variables (with renaming and defaults). It makes function parameters self-documenting, reduces repetition and is used everywhere in React (props, hooks).
Summary
- Objects hold key: value pairs; dot for fixed keys, brackets for dynamic keys.
- Methods use this; avoid arrow functions as methods.
- Object.keys/values/entries, destructuring and spread are daily tools.
- JSON.stringify to send, JSON.parse to receive.
Day 8: map, filter, reduce, find and sort – the array superpowers behind every cart and report.
