147

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
  • 19,327
  • 10
  • 37
  • 52
Hitesh Prajapati
  • 2,762
  • 8
  • 23
  • 29
  • 1
    i think you still got some json errors – S L Mar 15 '11 at 10:30
  • 4
    possible duplicate of [Remove a JSON attribute](http://stackoverflow.com/questions/1219630/remove-a-json-attribute) – ChrisF Sep 30 '12 at 20:26
  • 1
    I answered the question, you might want to have a look at it. I added the answer because many people don't take into consideration how garbage collection works. – Games Brainiac Jul 23 '13 at 17:36
  • @ChrisF - not a duplicate since delete will create an "undefined" item in the array – mplungjan Nov 03 '16 at 07:38
  • http://stackoverflow.com/questions/2912150/deleteing-json-object-from-an-array-creates-undefined-objects – mplungjan Nov 03 '16 at 07:39

13 Answers13

234
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,794
  • 3
  • 27
  • 35
  • 12
    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
  • 5
    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
  • 10
    using *delete* will leave a null element in the array – MikeL Sep 11 '17 at 19:05
30

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
  • 169,008
  • 28
  • 173
  • 236
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,447
  • 3
  • 20
  • 37
18

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,597
  • 4
  • 18
  • 26
13

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,426
  • 2
  • 21
  • 27
  • 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.

Marian
  • 3,789
  • 2
  • 26
  • 36
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • 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
7
  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
  • 914,110
  • 126
  • 1,211
  • 1,335
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,605
  • 19
  • 14
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,164
  • 2
  • 18
  • 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
  • 365
  • 5
  • 16
1

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.

CCC
  • 339
  • 2
  • 6
0

try this

json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
Kamran Ul Haq
  • 23
  • 1
  • 4
0

A descent Solution is here My JSON array is

const [myData, setData] = useState([{username:'faisalamin', share:20}, {username:'john', share:80}])

I want to delete john on a button click in renderItem or in .map

const _deleteItem = (item) => {
                    const newData = myData.filter(value => { return value.username !== item.username });
                    setData(newData);
            }
Faisal Amin
  • 91
  • 1
  • 5