First off, your quoted code is not JSON. Your code is JavaScript object literal notation. JSON is a subset of that designed for easier parsing.
您的代码定义了一个对象(data
),其中包含一个对象数组(items
)(每个对象都有id
、name
和type
).
You don't need or want jQuery for this, just JavaScript.
Adding an item:
data.items.push(
{id: "7", name: "Douglas Adams", type: "comedy"}
);
这增加了结局.参见下面的中间添加.
Removing an item:
有几种方法.splice
法是最通用的:
data.items.splice(1, 3); // Removes three items starting with the 2nd,
// ("Witches of Eastwick", "X-Men", "Ordinary People")
splice
修改原始数组,并返回已删除项的array.
Adding in the middle:个
splice
actually does both adding and removing. The signature of the splice
method is:
removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
index
- the index at which to start making changes
num_to_remove
-从该索引开始,删除这么多条目
addN
- ...and then insert these elements
所以我可以在第三个位置添加一个项目,如下所示:
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"}, // <== The new item
{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"}
]};
You can remove some and add some at once:
data.items.splice(1, 3,
{id: "7", name: "Douglas Adams", type: "comedy"},
{id: "8", name: "Dick Francis", type: "mystery"}
);
...which means: Starting at index 1, remove three entries, then add these two entries. Which results in:
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"}
]};