小编典典

使用jQuery从JavaScript对象添加/删除项目

javascript

我有一个JavaScript对象,如下所示:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", 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"}
]};

如果我想在此列表中添加/删除项目,我将如何使用jQuery进行处理?客户希望该列表是可动态修改的。


阅读 280

收藏
2020-05-01

共1个答案

小编典典

首先,您引用的代码 不是
JSON。您的代码是JavaScript对象文字表示法。JSON是为简化解析而设计的子集。

您的代码定义的对象(data包含数组()items对象)(每个都具有idnametype)。

您不需要或不需要jQuery,而只需JavaScript。

添加项目:

data.items.push(
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

这增加了最后。参见下面的中间添加。

删除项目:

有几种方法。该splice方法最通用:

data.items.splice(1, 3); // Removes three items starting with the 2nd,
                         // ("Witches of Eastwick", "X-Men", "Ordinary People")

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"},     // <== 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"}
]};

您可以删除并立即添加一些:

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"}
]};
2020-05-01