Asked 7 years ago
5 Jan 2017
Views 1162
Rasi

Rasi posted

How to Remove a JSON attribute in JavaScript ?



var jsonObj = {'serachResult' : {'title1' : 'description1', 'title2' : 'description2','title3' : 'description3',}}

suppose i need to remove title2 or description2 or full pair of second search result .
so it end result should be


var jsonObj = {'serachResult' : {'title1' : 'description1','title3' : 'description3',}}

or

var jsonObj = {'serachResult' : {'title1' : 'description1', 'title2' : '','title3' : 'description3',}}


how to remove a key or value or full key / value pair from JSON which is received by Ajax in JavaScript ?
jabber

jabber
answered Apr 24 '23 00:00

To remove an attribute from a JSON object in JavaScript, you can use the delete keyword followed by the name of the attribute you want to remove.

For example:



const data = {
  name: "John",
  age: 30,
  city: "New York"
};

delete data.age;

console.log(data)
;
In this example, we have a JSON object called data with three attributes: name , age , and city . To remove the age attribute, we use the delete keyword followed by data.age . This will remove the age attribute from the data object.

After running the code, the console.log(data) statement will output the following object:



 name: "John",
  city: "New York"
}

As you can see, the age attribute has been removed from the data object.

It's important to note that using delete to remove an attribute from a JSON object modifies the object in place. If you need to create a new object without a certain attribute, you can use techniques such as destructuring or the Object.assign( ) method to create a new object with only the attributes you want.
Post Answer