Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟨 Days 1–7 – JavaScript की नींव  ·  दिन 07

दिन 7: Objects, Destructuring, Spread और JSON

⏱ 90 min📶 Beginner🎯 100% self-study
दिन 7 / 30

✅ आज आप सीखेंगे

  • 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 बनाना और पढ़ना

JavaScript
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
Kaju Katli 900 15 days dry undefined

जोड़ना, बदलना, हटाना, जाँचना

JavaScript
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);
{ id: 1042, total: 1890, status: 'packing' } true false 5

Methods और this

JavaScript
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());
1300 2 × Ghewar = ₹1300
⚠️ Methods के रूप में arrow functions

total: () => this.price * this.qty न लिखें। Arrow functions का अपना this नहीं होता, तो this.price undefined होगा। Method shorthand total() { … } लें। Day 17 this को पूरा समझाता है।

Objects पर loop

JavaScript
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');
[ 'kaju', 'ghewar', 'rasmalai', 'kalakand' ] [ 25, 8, 12, 0 ] kaju 25 kg ghewar 8 kg rasmalai 12 kg kalakand OUT OF STOCK Total stock: 45 kg

Destructuring और spread

JavaScript
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));
Riya 9829012345 Jaipur not given Kaju Ladoo 9829012345 → 9876543210 Riya – PIN 302003
🧠 Spread shallow होता है

{ ...customer } सिर्फ़ ऊपरी स्तर copy करता है; updated.address अब भी customer.address वाला ही object है। पूरी deep copy के लिए structuredClone(customer)।

Objects के arrays – असली data

JavaScript
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 })));
Revenue collected: ₹4200 Remind: Rahul ┌─────────┬──────┬──────────┬───────┐ │ (index) │ id │ customer │ total │ ├─────────┼──────┼──────────┼───────┤ │ 0 │ 1041 │ 'Aarti' │ 1800 │ │ 1 │ 1042 │ 'Rahul' │ 650 │ │ 2 │ 1043 │ 'Sana' │ 2400 │ └─────────┴──────┴──────────┴───────┘

JSON – data कैसे यात्रा करता है

JavaScript
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
{"id":1043,"items":[{"name":"Rasmalai","qty":2}],"paid":true} string Rasmalai object { "id": 1043, "items": [ { "name": "Rasmalai", "qty": 2 } ], "paid": true }
JSON नियमउदाहरण
Keys हमेशा double quotes में{"name": "Ghewar"}
Strings सिर्फ़ double quotes में"Jaipur" ('Jaipur' नहीं)
मान्य valuesstring, number, true/false, null, object, array
मान्य नहींfunctions, undefined, comments, trailing commas
DatesStrings के रूप में: "2026-10-25T10:30:00Z"

असली task: object से product card

HTML + JavaScript
<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>
▶  Destructured parameters + template literal → HTML

🏅 आज के Job Skills

✔ Properties और methods वाले objects से data✔ Properties पढ़ना, जोड़ना, बदलना और हटाना✔ Object.keys/values/entries से loop; destructure और spread✔ Objects के arrays और JSON के साथ काम

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: name, roll, marks {maths, science, english} और average() method वाला student object बनाएँ। “Riya (Roll 12): 84.3” print करें।
Solution देखें
JavaScript
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()}`);
Riya (Roll 12): 84.3
Task 2: यह JSON parse करके हर item line print करें: {"orderId":"SS1","items":[{"name":"Ladoo","qty":2,"price":500},{"name":"Kaju Katli","qty":1,"price":900}]}
Solution देखें
JavaScript
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}`);
Ladoo: 2 × ₹500 = ₹1000 Kaju Katli: 1 × ₹900 = ₹900 SS1 total ₹1900
Task 3: 5 PIN codes → delivery charge वाला object बनाएँ और लिखे गए PIN का charge खोजें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. Variable k में रखी key पढ़ें:
Brackets variable पढ़ते हैं।
2. JSON.parse बदलता है…
stringify उल्टा है।
3. const { a = 5 } = {} में a =
ग़ायब हो तो default।
4. कौन valid JSON नहीं है?
Single quotes मान्य नहीं।
5. Object.entries लौटाता है…
for…of के साथ बढ़िया।

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।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Object या Map?
Fixed आकार वाले records (product) के लिए साधारण objects। जब keys dynamic हों, strings न हों, या बार-बार जोड़ी/हटाई जाएँ तो Map।
console.table क्या है?
DevTools/Node helper जो objects के arrays को table के रूप में print करता है – API data debug करने के लिए बढ़िया।
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 8: map, filter, reduce, find और sort आपकी प्रगति: 7 / 30 (23%) · Lesson 8 / 30 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें