简体   繁体   English

使用Jquery插入,更新和删除JSON对象

[英]Insert , Update and Delete JSON object using Jquery

I have this JSON object . 我有这个JSON对象。

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 插入JSON对象是

                 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? 我的问题是, 有人可以告诉我如何针对此JSON对象执行更新和删除操作吗?

Because you tagged this question with "jquery" I'm going to answer using jquery functions. 因为您用“ jquery”标记了这个问题,所以我将使用jquery函数进行回答。

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). 我认为您要问的是如何使用jquery更新/删除对象数组中的指定对象(请注意,变量obj实际上是对象数组)。 The jquery function grep is good for finding the correct object within an array of objects. jQuery函数grep非常适合在对象数组中找到正确的对象。 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. 您可以使用grep从对象数组中删除一个对象。 Alternatively, you could use splice like this: 另外,您可以像这样使用splice

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

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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