Open In App

How to delete an index from JSON Object ?

Last Updated : 13 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Deleting an index from a JSON object involves removing a specific key-value pair from the object structure. This is often done to clean up data, remove sensitive information, or modify the object for specific use cases, ensuring only relevant information remains accessible.

Now, to delete any index from this JSON object, we will learn different methods that are explained below – 

Using delete property

The delete operator in JavaScript is used to remove a property from an object. By using delete obj.key, you can delete a specific key-value pair from the object, modifying its structure and reducing the total number of properties it contains.

Syntax

delete object.property or
delete object['property'] or
delete object[index]

Example : In this example we defines a students array with objects, uses the delete operator to remove the first object entirely and the phone property from the second object, then logs the changes.

JavaScript
let students = [
    { "student": "Akshit", "address": "Moradabad", "phone": "98760" },
    { "student": "Nikita", "address": "Lucknow", "phone": "98754" }
];

console.log("Before deletion:", students);

delete students[0]; // Deletes the entire object at index 0
delete students[1].phone; // Deletes the 'phone' property at index 1

console.log("After deletion:", students);

Output
Before deletion: [
  { student: 'Akshit', address: 'Moradabad', phone: '98760' },
  { student: 'Nikita', address: 'Lucknow', phone: '98754' }
]
After deletion: [ <1 empty item>, { student: 'Nikita', address: 'Lucknow' } ]

Using Object.fromEntries() with Object.entries() and filter()

To delete a key from a JSON object using Object.fromEntries(), Object.entries(), and filter(), first convert the object into an array of key-value pairs with Object.entries(). Then, use filter() to remove the desired key and reconstruct the object with Object.fromEntries().

Syntax

const filteredObj = Object.fromEntries(
Object.entries(obj).filter(([key, value]) => key !== 'b')
);

Example : In this example we converts the object into an array of key-value pairs, filters out the key ‘b’, and then converts it back into an object without the excluded key.

JavaScript
// Original object
const obj = {
    a: 1,
    b: 2,
    c: 3
};

// Remove the key 'b' from the object
const filteredObj = Object.fromEntries(
    Object.entries(obj).filter(([key, value]) => key !== 'b')
);

console.log(filteredObj); 

Output
{ a: 1, c: 3 }


Next Article

Similar Reads