[英]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.