[英]Insert , Update and Delete JSON object using Jquery
我有这个JSON对象。
json_elements = JSON.stringify(obj);
值是:
[{"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}]
插入JSON对象是
obj.push({
pid: pid,
qty: qty,
Pname: Pname,
uniteV: uniteV
});
我的问题是, 有人可以告诉我如何针对此JSON对象执行更新和删除操作吗?
因为您用“ jquery”标记了这个问题,所以我将使用jquery函数进行回答。
我认为您要问的是如何使用jquery更新/删除对象数组中的指定对象(请注意,变量obj
实际上是对象数组)。 jQuery函数grep
非常适合在对象数组中找到正确的对象。 在数组中找到正确的对象后,您可以简单地更新该对象。
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
};
您可以使用grep
从对象数组中删除一个对象。 另外,您可以像这样使用splice
:
$.each(myArray, function(i){
if(myArray[i].pid == pidThatYouWantToDelete) {
myArray.splice(i,1);
return false;
};
});
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.