Remove JSON element

JavascriptJson

Javascript Problem Overview


I want to remove JSON element or one whole row from JSON.

I have following JSON string:

{
   "result":[
       {
           "FirstName": "Test1",
           "LastName":  "User",
       },
       {
           "FirstName": "user",
           "LastName":  "user",
       },
       {
           "FirstName": "Ropbert",
           "LastName":  "Jones",
       },
       {
           "FirstName": "hitesh",
           "LastName":  "prajapti",
       }
   ]
}

Javascript Solutions


Solution 1 - Javascript

var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.

You can use splice to remove elements from an array.

Solution 2 - Javascript

Do NOT have trailing commas in your OBJECT (JSON is a string notation)

UPDATE: you need to use array.splice and not delete if you want to remove items from the array in the object. Alternatively filter the array for undefined after removing

var data = {
  "result": [{
    "FirstName": "Test1",
    "LastName": "User"
  }, {
    "FirstName": "user",
    "LastName": "user"
  }]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.


data = {
  "result": [{
    "FirstName": "Test1",
    "LastName": "User"
  }, {
    "FirstName": "user",
    "LastName": "user"
  }]
}

console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.

Solution 3 - Javascript

You can try to delete the JSON as follows:

var bleh = {first: '1', second: '2', third:'3'}

alert(bleh.first);

delete bleh.first;

alert(bleh.first);

Alternatively, you can also pass in the index to delete an attribute:

delete bleh[1];

However, to understand some of the repercussions of using deletes, have a look here

Solution 4 - Javascript

For those of you who came here looking for how to remove an object from an array based on object value:

let users = [{name: "Ben"},{name: "Tim"},{name: "Harry"}];

let usersWithoutTim = users.filter(user => user.name !== "Tim");

// The old fashioned way:

for (let [i, user] of users.entries()) {
  if (user.name === "Tim") {
    users.splice(i, 1); // Tim is now removed from "users"
  }
}

Note: These functions will remove all users named Tim from the array.

Solution 5 - Javascript

I recommend splice method to remove an object from JSON objects array.

jQuery(json).each(function (index){
        if(json[index].FirstName == "Test1"){
            json.splice(index,1); // This will remove the object that first name equals to Test1
            return false; // This will stop the execution of jQuery each loop.
        }
});

I use this because when I use delete method, I get null object after I do JSON.stringify(json)

Solution 6 - Javascript

All the answers are great, and it will do what you ask it too, but I believe the best way to delete this, and the best way for the garbage collector (if you are running node.js) is like this:

var json = { <your_imported_json_here> };
var key = "somekey";
json[key] = null;
delete json[key];

This way the garbage collector for node.js will know that json['somekey'] is no longer required, and will delete it.

Solution 7 - Javascript

  1. Fix the errors in the JSON: http://jsonlint.com/
  2. Parse the JSON (since you have tagged the question with JavaScript, use json2.js)
  3. Delete the property from the object you created
  4. Stringify the object back to JSON.

Solution 8 - Javascript

As described by @mplungjan, I though it was right. Then right away I click the up rate button. But by following it, I finally got an error.

<script>
var data = {"result":[
  {"FirstName":"Test1","LastName":"User","Email":"[email protected]","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
  {"FirstName":"user","LastName":"user","Email":"[email protected]","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
  {"FirstName":"Ropbert","LastName":"Jones","Email":"[email protected]","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
  {"FirstName":"hitesh","LastName":"prajapti","Email":"[email protected]","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
  ]
}
alert(data.result)
delete data.result[3]
alert(data.result)
</script>

Delete is just remove the data, but the 'place' is still there as undefined.

I did this and it works like a charm :

data.result.splice(2,1);  

meaning : delete 1 item at position 3 ( because array is counted form 0, then item at no 3 is counted as no 2 )

Solution 9 - Javascript

Try this following

var myJSONObject ={"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
console.log(myJSONObject);
console.log(myJSONObject.ircEvent);
delete myJSONObject.ircEvent 
delete myJSONObject.regex 
console.log(myJSONObject);

Solution 10 - Javascript

if we want to remove one attribute say "firstName" from the array we can use map function along with delete as mentioned above

   var result= [
       {
           "FirstName": "Test1",
           "LastName":  "User",
       },
       {
           "FirstName": "user",
           "LastName":  "user",
       },
       {
           "FirstName": "Ropbert",
           "LastName":  "Jones",
       },
       {
           "FirstName": "hitesh",
           "LastName":  "prajapti",
       }
   ]

result.map( el=>{
    delete el["FirstName"]
})
console.log("OUT",result)

Solution 11 - Javascript

try this

json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)

Solution 12 - Javascript

Could you possibly use filter? Say you wanted to remove all instances of Ropbert

let result = [
   {
       "FirstName": "Test1",
       "LastName":  "User",
   },
   {
       "FirstName": "user",
       "LastName":  "user",
   },
   {
       "FirstName": "Ropbert",
       "LastName":  "Jones",
   },
   {
       "FirstName": "hitesh",
       "LastName":  "prajapti",
   }
   ]

result = result.filter(val => val.FirstName !== "Ropbert")

(result now contains)

[
   {
       "FirstName": "Test1",
       "LastName":  "User",
   },
   {
       "FirstName": "user",
       "LastName":  "user",
   },
   {
       "FirstName": "hitesh",
       "LastName":  "prajapti",
   }
   ] 

You can add further values to narrow down the items you remove, for example if you want to remove on first and last name then you could do this:

result = result.filter(val => !(val.FirstName === "Ropbert" && val.LastName === "Jones"))

Although as noted, if you have 4 'Ropbert Jones' in your array, all 4 instances would be removed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHitesh PrajapatiView Question on Stackoverflow
Solution 1 - JavascriptdteohView Answer on Stackoverflow
Solution 2 - JavascriptmplungjanView Answer on Stackoverflow
Solution 3 - JavascriptFaraxView Answer on Stackoverflow
Solution 4 - JavascriptChrisView Answer on Stackoverflow
Solution 5 - JavascriptDisapamokView Answer on Stackoverflow
Solution 6 - JavascriptGames BrainiacView Answer on Stackoverflow
Solution 7 - JavascriptQuentinView Answer on Stackoverflow
Solution 8 - JavascriptSulung NugrohoView Answer on Stackoverflow
Solution 9 - JavascriptabcdView Answer on Stackoverflow
Solution 10 - JavascriptRaghu VallikkatView Answer on Stackoverflow
Solution 11 - JavascriptKamran Ul HaqView Answer on Stackoverflow
Solution 12 - JavascriptChrisView Answer on Stackoverflow