-->

JavaScript - JSON Part 5: Modifying and Updating JSON Data

How to Modify JSON Data?

Once converted into a JavaScript object, JSON data can be updated, added to, or deleted.

Example 7: Updating JSON Data

const car = { brand: "Toyota", model: "Corolla", year: 2020 };

car.year = 2024; // Update year

console.log(car);

Explanation:

The year property is modified from 2020 to 2024.

JSON data can be dynamically updated in JavaScript.

Example 8: Adding and Removing Properties

const student = { name: "John", age: 18 };

student.grade = "A"; // Adding a new property

delete student.age; // Removing a property

console.log(student); 

Explanation:

student.grade = "A" adds a new key-value pair.

delete student.age removes the age property.

Example 9: Looping Through JSON Data

You can loop through JSON data dynamically:

const user = { name: "Sarah", city: "Los Angeles", age: 28 };

for (let key in user) {

    console.log(`${key}: ${user[key]}`);

}

Explanation:

The loop prints all keys and values dynamically.

Useful for working with unknown JSON structures.