我有这个JSON对象。
json_elements = JSON.stringify(obj);
VALUE是:
[{"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对象更新和删除操作?
答案 0 :(得分:0)
因为你用“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;
};
});
希望这有帮助