首先,您引用的代码不是JSON。您的代码是JavaScript对象文字表示法。JSON是为简化解析而设计的子集。
您的代码定义了一个对象(data
),其中包含一个对象数组(items
)(每个对象都带有一个id
,name
和type
)。
您不需要或不需要jQuery,而只需JavaScript。
添加项目:
data.items.push(
{id: "7", name: "Douglas Adams", type: "comedy"}
);
这增加了最后。参见下面的中间添加。
删除项目:
有几种方法。该splice
方法最通用:
data.items.splice(1, 3);
splice
修改原始数组,并返回您删除的项目的数组。
在中间添加:
splice
实际上既添加又删除。该splice
方法的签名是:
removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
index
-开始进行更改的索引
num_to_remove
-从该索引开始,删除这么多条目
addN
-...然后插入这些元素
所以我可以在第3个位置添加一个项目,如下所示:
data.items.splice(2, 0,
{id: "7", name: "Douglas Adams", type: "comedy"}
);
这是说:从索引2开始,删除零个项目,然后插入以下项目。结果看起来像这样:
var data = {items: [
{id: "1", name: "Snatch", type: "crime"},
{id: "2", name: "Witches of Eastwick", type: "comedy"},
{id: "7", name: "Douglas Adams", type: "comedy"},
{id: "3", name: "X-Men", type: "action"},
{id: "4", name: "Ordinary People", type: "drama"},
{id: "5", name: "Billy Elliot", type: "drama"},
{id: "6", name: "Toy Story", type: "children"}
]};
您可以删除并立即添加一些:
data.items.splice(1, 3,
{id: "7", name: "Douglas Adams", type: "comedy"},
{id: "8", name: "Dick Francis", type: "mystery"}
);
...这意味着:从索引1开始,删除三个条目,然后添加这两个条目。结果是:
var data = {items: [
{id: "1", name: "Snatch", type: "crime"},
{id: "7", name: "Douglas Adams", type: "comedy"},
{id: "8", name: "Dick Francis", type: "mystery"},
{id: "4", name: "Ordinary People", type: "drama"},
{id: "5", name: "Billy Elliot", type: "drama"},
{id: "6", name: "Toy Story", type: "children"}
]};