Featured
- Get link
- X
- Other Apps
Day 33 : Objects & JSON
📘 Day 33 — Objects & JSON (In-depth)
Objects are fundamental for modeling real-world data in JavaScript. Today we’ll cover object creation, property access, methods, nested objects, prototypal basics (brief), and JSON (convert objects to/from strings), with practical examples and exercises.
1 — Creating Objects
// Object literal
const person = {
name: "Rahul",
age: 23,
skills: ["HTML","CSS","JS"],
greet: function(){ return "Hello, " + this.name; }
};
// Using Object constructor
const obj = new Object();
obj.key = 'value';
2 — Accessing Properties
Two ways: dot notation and bracket notation.
console.log(person.name); // Rahul console.log(person['age']); // 23 let key = 'skills'; console.log(person[key]); // ["HTML","CSS","JS"]
3 — Adding, Updating, Deleting
person.location = 'India'; // add person.age = 24; // update delete person.location; // remove
4 — Methods & this
Objects can contain functions (methods). The this keyword refers to the object in most cases.
const counter = {
value: 0,
increment() { this.value++; },
get() { return this.value; }
};
counter.increment();
console.log(counter.get()); // 1
5 — Nested Objects & Access
const user = {
name: 'Asha',
address: { city: 'Delhi', zip: 110001 },
preferences: { theme: 'dark' }
};
console.log(user.address.city); // Delhi
6 — JSON (JavaScript Object Notation)
JSON is a string format to store/transfer structured data (commonly used in APIs). Convert between object and JSON string using JSON.stringify and JSON.parse.
const obj = {name:'Rahul', age:23};
const jsonString = JSON.stringify(obj); // '{"name":"Rahul","age":23}'
const parsed = JSON.parse(jsonString); // {name: 'Rahul', age: 23}
Be careful: JSON supports only certain types (objects, arrays, strings, numbers, booleans, null). Functions and undefined are not preserved in JSON.
7 — Useful Object Methods
Object.keys(obj)— returns array of keysObject.values(obj)— returns array of valuesObject.entries(obj)— returns [[key,value], ...]Object.assign(target, ...sources)— shallow merge
const settings = {a:1};
const more = {b:2};
const merged = Object.assign({}, settings, more); // {a:1,b:2}
console.log(Object.keys(person)); // ["name","age","skills","greet"]
🧠 Live Editor — Objects & JSON Playground
Test creating objects, converting to JSON, and iterating with Object.entries.
Practice Tasks
- Write
deepClone(obj)(shallow via JSON methods is acceptable) and explain its limitations. - Given array of users, build index (object) by id:
{ id: user }. - Fetch remote JSON (mock with local string) and render it into a simple list (simulate API with
JSON.parse).
Popular Posts
📘 Day 36: Understanding the DOM (Document Object Model)
- Get link
- X
- Other Apps
Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
Comments
Post a Comment