दिन 7: Objects, Destructuring, Spread और JSON
✅ आज आप सीखेंगे
- key: value जोड़ों से असली चीज़ें दर्शाना
- Dot बनाम bracket access, properties जोड़ना/बदलना/हटाना
- Methods और this की पहली झलक
- Object.keys / values / entries, destructuring, spread
- Objects के arrays और JSON – APIs की भाषा
🏢 असली दुनिया में
Product एक value नहीं – उसका नाम, price, category, stock और rating होता है। Order में customer, items और total होता है। असली apps (और internet का हर API) data को objects और objects के arrays के रूप में रखते हैं। आज के बाद आप backend developer का भेजा कोई भी JSON response पढ़ सकेंगे।
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 → undefinedजोड़ना, बदलना, हटाना, जाँचना
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 और 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());total: () => this.price * this.qty न लिखें। Arrow functions का अपना this नहीं होता, तो this.price undefined होगा। Method shorthand total() { … } लें। Day 17 this को पूरा समझाता है।
Objects पर loop
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 और 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 } सिर्फ़ ऊपरी स्तर copy करता है; updated.address अब भी customer.address वाला ही object है। पूरी deep copy के लिए structuredClone(customer)।
Objects के arrays – असली 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 – data कैसे यात्रा करता है
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 नियम | उदाहरण |
|---|---|
| Keys हमेशा double quotes में | {"name": "Ghewar"} |
| Strings सिर्फ़ double quotes में | "Jaipur" ('Jaipur' नहीं) |
| मान्य values | string, number, true/false, null, object, array |
| मान्य नहीं | functions, undefined, comments, trailing commas |
| Dates | Strings के रूप में: "2026-10-25T10:30:00Z" |
असली task: object से product card
<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
Practice tasks
🏋️ Practice – ख़ुद करें
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}]}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 – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
Object की deep copy कैसे करें?
structuredClone(obj) (आधुनिक, dates, maps, nested objects संभालता है); JSON.parse(JSON.stringify(obj)) सिर्फ़ साधारण JSON-safe data के लिए, functions, undefined और dates खो देता है। Spread/Object.assign shallow हैं।
Destructuring क्या है और क्यों उपयोगी?
Properties या array items को variables में खोलने का syntax (नाम बदलने और defaults के साथ)। Function parameters ख़ुद समझाने वाले बनते हैं, दोहराव घटता है और React में हर जगह इस्तेमाल होता है (props, hooks)।
सारांश
- Objects key: value जोड़े रखते हैं; fixed keys के लिए dot, dynamic के लिए brackets।
- Methods this लेते हैं; methods के रूप में arrow functions से बचें।
- Object.keys/values/entries, destructuring और spread रोज़ के औज़ार।
- भेजने को JSON.stringify, पाने को JSON.parse।
Day 8: map, filter, reduce, find और sort – हर cart और report के पीछे की array superpowers।
