简体   繁体   中英

Insert , Update and Delete JSON object using Jquery

I have this JSON object .

json_elements = JSON.stringify(obj);

VALUE is :

  [{"pid":"2","qty":1,"Pname":"Jelly Doughnuts","uniteV":36},{"pid":"34","qty":1,"Pname":"Loukoumades Donuts","uniteV":9},{"pid":"32","qty":1,"Pname":"Bismark Doughnut","uniteV":6},{"pid":"34","qty":1,"Pname":"Loukoumades Donuts","uniteV":9},{"pid":"33","qty":1,"Pname":"Maple Bar Donuts","uniteV":3}]

Insert into JSON object is

                 obj.push({
                        pid: pid,
                        qty: qty,
                        Pname: Pname,
                        uniteV: uniteV
                    });

MY question is CAN any one tell me HOW TO UPDATE AND DELETE operation done for exactly this JSON object?

Because you tagged this question with "jquery" I'm going to answer using jquery functions.

I think that what you are trying to ask is how can you use jquery to update/delete a specified object in your array of objects (note that your variable obj is actually an array of objects). The jquery function grep is good for finding the correct object within an array of objects. Once you find the correct object in the array you can simply update that object.

var myArray = obj; //you're really working with an array of objects instead of one objects
var result = $.grep(myArray, function(e){ return e.pid == pidToUpdate; });
if (result.length == 0) {
  // the object wasn't in the array of objects
} else if (result.length == 1) {
  // there was a single matching object, and we can now update whatever attribute we want
  result[0].attributeToUpdate = newValue
} else {
  // multiple items found.  Do with them whatever you want
};

You can use grep to delete an object from an array of objects. Alternatively, you could use splice like this:

$.each(myArray, function(i){
  if(myArray[i].pid == pidThatYouWantToDelete) {
      myArray.splice(i,1);
      return false;
  };
});

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM