136

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",
       }
   ]
}
Syscall
  • 18,131
  • 10
  • 32
  • 49
Hitesh Prajapati
  • 2,636
  • 7
  • 22
  • 29

12 Answers12

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

You can use splice to remove elements from an array.

dteoh
  • 5,582
  • 2
  • 25
  • 35
  • 11
    Why are always the worst answers at the top? Could it possibly be the rep points? I searched. I found. You had the correct answer. – Eric Leroy Nov 02 '12 at 03:01
  • 4
    I don't get this answer. Where's "foo" in the test data? – Tony Oct 04 '13 at 02:45
  • 11
    Where's foo in the test data? Well, the first line is actually pseudocode. Instead of json = {...}, it would be something like json = {foo: 'value'} – aharris88 Mar 20 '14 at 23:38
  • 6
    delete json[key]; ? How many "FirstName" in given example? Wrong answer. – EGurelli Nov 09 '16 at 11:19
  • The question (at the time of answering) was ambiguous and did not ask for a particular key of an object or row of the array to be removed. The answer I have given provides sufficient information to solve this homework problem. – dteoh Nov 09 '16 at 23:42
  • 9
    using *delete* will leave a null element in the array – MikeL Sep 11 '17 at 19:05
28

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.
mplungjan
  • 155,085
  • 27
  • 166
  • 222
19

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

Farax
  • 1,419
  • 2
  • 20
  • 36
13

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.

Chris
  • 1,489
  • 4
  • 17
  • 24
12

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)

Disapamok
  • 1,356
  • 2
  • 19
  • 26
  • 1
    Splice should be the accepted answer, delete replaces the json document with a NULL insertion.... I wanted delete to delete it -- splice will. – Andy Dec 20 '18 at 18:48
8

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.

hlfrmn
  • 3,435
  • 1
  • 25
  • 33
Games Brainiac
  • 75,856
  • 32
  • 131
  • 189
  • I've read about doing it this way too, but I cannot get this to work. It still leaves the null references – K20GH Oct 20 '17 at 10:12
6

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":"test@test.com","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
  {"FirstName":"user","LastName":"user","Email":"u@u.com","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
  {"FirstName":"Ropbert","LastName":"Jones","Email":"Robert@gmail.com","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
  {"FirstName":"hitesh","LastName":"prajapti","Email":"h.prajapati@zzz.com","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 )

Sulung Nugroho
  • 1,419
  • 16
  • 13
6
  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.
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
5

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);
abcd
  • 3,134
  • 2
  • 17
  • 13
2

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)
Raghu Vallikkat
  • 345
  • 4
  • 13
0

try this

json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)
Jitesh Prajapati
  • 2,661
  • 4
  • 28
  • 47
Kamran Ul Haq
  • 25
  • 1
  • 4
0

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.

Chris
  • 119
  • 1
  • 4