Thursday, 28 May 2020

How to delete an item from the JSON Array? | JSON Tutorial

Enjoying these coding tutorials?

Subscribe to Ram N Java on YouTube for simple, step-by-step guides on JavaScript and JSON!

🔔 Subscribe to the Channel

Deleting an Item from a JSON Array

When working with JSON data, removing items from an array is a regular task—whether a user removes an item from their cart or removes an obsolete entry from a settings list.

In JavaScript, the delete operator allows you to remove a specific array element by targeting its index position directly.

How the delete Operator Works

Arrays use zero-based indexing, where the first item starts at index 0. Using delete on an array element removes that item's value while keeping the original length of the array intact:

  • The targeted position becomes undefined.
  • The remaining elements do not shift their index positions.

Step-by-Step Code Example

Here is a clear example demonstrating how to remove an item from an array inside a JSON object:

// Sample JSON object with an array
const myObject = {
  "name": "John",
  "age": 30,
  "cars": ["Ford", "BMW", "Fiat"]
};

// Delete the second item (index 1)
delete myObject.cars[1];

// Inspect the updated array
console.log(myObject.cars);
console.log(myObject.cars[1]); // Output: undefined

Key Observations:

  • Value Removed: The value "BMW" at index 1 is successfully cleared.
  • Index Preserved: Accessing myObject.cars[1] returns undefined.
  • Remaining Items Intact: The elements at index 0 ("Ford") and index 2 ("Fiat") stay at their original positions.

Summary

The delete keyword provides a fast, straightforward way to clear specific elements in JSON arrays without altering the index numbers of other items.

Related Tutorials from Ram N Java

Check out these related guides to master more JSON array techniques:

No comments:

Post a Comment

Tutorials