First off, your quoted code is not JSON.
(首先,您引用的代码不是 JSON。)
Your code is JavaScript object literal notation.(您的代码是JavaScript对象文字表示法。)
JSON is a subset of that designed for easier parsing.(JSON是为便于解析而设计的子集。)
Your code defines an object ( data
) containing an array ( items
) of objects (each with an id
, name
, and type
).
(您的代码定义了一个包含对象数组( items
)的对象( data
)(每个对象都有一个id
, name
和type
)。)
You don't need or want jQuery for this, just JavaScript.
(你不需要或想要jQuery,只需JavaScript。)
Adding an item:
(添加项目:)
data.items.push(
{id: "7", name: "Douglas Adams", type: "comedy"}
);
That adds to the end.
(这增加了结果。)
See below for adding in the middle.(请参阅下面的中间添加。)
Removing an item:
(删除项目:)
There are several ways.
(有几种方法。)
The splice
method is the most versatile:(splice
方法是最通用的:)
data.items.splice(1, 3); // Removes three items starting with the 2nd,
// ("Witches of Eastwick", "X-Men", "Ordinary People")
splice
modifies the original array, and returns an array of the items you removed.
(splice
修改原始数组,并返回您删除的项的数组。)
Adding in the middle:
(在中间添加:)
splice
actually does both adding and removing.
(splice
实际上同时添加和删除。)
The signature of the splice
method is:(splice
方法的签名是:)
removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
So I can add an item in the 3rd position like this:
(所以我可以在第3个位置添加一个项目,如下所示:)
data.items.splice(2, 0,
{id: "7", name: "Douglas Adams", type: "comedy"}
);
What that says is: Starting at index 2, remove zero items, and then insert this following item.
(这是说:从索引2开始,删除零项,然后插入以下项。)
The result looks like this:(结果如下:)
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.
(...表示:从索引1开始,删除三个条目,然后添加这两个条目。)
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"}
]};