我有这个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对象的操作吗?
发布于 2014-02-24 20:12:05
因为您用" 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;
};
});希望这能有所帮助
https://stackoverflow.com/questions/21994889
复制相似问题