I have a JavaScript object as follows:
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"}
]};
If I wanted to add/remove items to this list, how would I go about it using jQuery? The client wants this list to be dynamically modifiable.
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.
Your code defines an object (
data) containing an array (items) of objects (each with anid,name, andtype).You don’t need or want jQuery for this, just JavaScript.
Adding an item:
That adds to the end. See below for adding in the middle.
Removing an item:
There are several ways. The
splicemethod is the most versatile:splicemodifies the original array, and returns an array of the items you removed.Adding in the middle:
spliceactually does both adding and removing. The signature of thesplicemethod is:index– the index at which to start making changesnum_to_remove– starting with that index, remove this many entriesaddN– …and then insert these elementsSo I can add an item in the 3rd position like this:
What that says is: Starting at index 2, remove zero items, and then insert this following item. The result looks like this:
You can remove some and add some at once:
…which means: Starting at index 1, remove three entries, then add these two entries. Which results in: