Learn about JavaScript objects, JSON data format, and object methods.
Example demonstrating object creation, manipulation, and JSON usage:
// Create a JavaScript object
const user = {
name: "Alice",
age: 25,
isAdmin: true,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
// Accessing properties and calling methods
console.log(user.name); // "Alice"
console.log(user.greet()); // "Hello, my name is Alice"
// Convert object to JSON
const jsonString = JSON.stringify(user);
console.log(jsonString);
// Convert JSON back to object
const parsedUser = JSON.parse(jsonString);
console.log(parsedUser.name); // "Alice"
This code demonstrates:
JSON.stringify().JSON.parse().JavaScript Objects: Collections of key-value pairs, where keys are strings and values can be any data type. Objects are used to represent real-world entities in code.
JSON: A data format derived from JavaScript object syntax, used for storing and exchanging data between servers and web applications.
Key Object Features:
Object.keys(obj) - Returns an array of object keys.Object.values(obj) - Returns an array of values.Object.entries(obj) - Returns an array of key-value pairs.JSON.stringify(obj) - Converts an object to a JSON string.JSON.parse(jsonStr) - Converts a JSON string to an object.Q1: Which method converts a JavaScript object to a JSON string?
JSON.parse()JSON.convert()JSON.stringify()Object.toJSON()Answer: C. JSON.stringify()
Q2: How do you access the value of a property name in an object user?
user.nameuser->nameuser(name)user::nameAnswer: A. user.name
Q3: What does JSON.parse() do?
Answer: B. Parses a JSON string to a JavaScript object.
Q4: Which method retrieves all the keys of an object?
Object.values()Object.entries()Object.keys()Object.getKeys()Answer: C. Object.keys()