使用 jQuery 从 JavaScript 对象中添加/删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4538269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding/removing items from a JavaScript object with jQuery
提问by Bug Magnet
I have a JavaScript object as follows:
我有一个 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"}
]};
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.
如果我想在此列表中添加/删除项目,我将如何使用 jQuery 进行操作?客户端希望这个列表可以动态修改。
回答by T.J. Crowder
First off, your quoted code is notJSON. Your code is JavaScript object literal notation. JSONis a subset of that designed for easier parsing.
首先,您引用的代码不是JSON。您的代码是 JavaScript 对象文字符号。JSON是专为更容易解析而设计的子集。
Your code defines an object (data
) containing an array (items
) of objects (each with an id
, name
, and type
).
您的代码定义的对象(data
包含数组()items
对象)(每个都具有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. The signature of the splice
method is:
splice
实际上做添加和删除。该splice
方法的签名是:
removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
index
- the index at which to start making changesnum_to_remove
- starting with that index, remove this many entriesaddN
- ...and then insert these elements
index
- 开始更改的索引num_to_remove
- 从该索引开始,删除这么多条目addN
- ...然后插入这些元素
So I can add an item in the 3rd position like this:
所以我可以像这样在第三个位置添加一个项目:
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. The result looks like this:
意思是:从索引 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:
...这意味着:从索引 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"}
]};
回答by Imrul
Spliceis good, everyone explain splice so I didn't explain it. You can also use deletekeyword in JavaScript, it's good. You can use $.grepalso to manipulate this using jQuery.
Splice很好,大家解释 splice 所以我就不解释了。你也可以在 JavaScript 中使用delete关键字,这很好。您也可以使用$.grep来使用 jQuery 操作它。
The jQuery Way :
jQuery 方式:
data.items = jQuery.grep(
data.items,
function (item,index) {
return item.id != "1";
});
DELETE Way:
删除方式:
delete data.items[0]
For Adding PUSH is better the splice, because splice is heavy weighted function. Splice create a new array , if you have a huge size of array then it may be troublesome. delete is sometime useful, after delete if you look for the length of the array then there is no change in length there. So use it wisely.
对于添加 PUSH 更好的是拼接,因为拼接是重加权函数。Splice 创建一个新数组,如果你有一个巨大的数组,那么它可能会很麻烦。delete 有时很有用,在删除之后,如果您查找数组的长度,则那里的长度没有变化。所以要明智地使用它。
回答by Peter Drinnan
If you are using jQuery you can use the extend function to add new items.
如果您使用 jQuery,您可以使用扩展功能添加新项目。
var olddata = {"fruit":{"apples":10,"pears":21}};
var newdata = {};
newdata['vegetables'] = {"carrots": 2, "potatoes" : 5};
$.extend(true, olddata, newdata);
This will generate:
这将生成:
{"fruit":{"apples":10,"pears":21}, "vegetables":{"carrots":2,"potatoes":5}};
回答by Guffa
That's not JSON at all, it's just Javascript objects. JSONis a text representation of data, that uses a subset of the Javascript syntax.
那根本不是 JSON,它只是 Javascript 对象。JSON是数据的文本表示,它使用 Javascript 语法的一个子集。
The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)
你找不到任何关于使用 jQuery 操作 JSON 的信息的原因是因为 jQuery 没有任何东西可以做到这一点,而且通常根本没有这样做。您以 Javascript 对象的形式操作数据,然后根据需要将其转换为 JSON 字符串。(不过,jQuery 确实有转换方法。)
What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items
to access the array.
您所拥有的只是一个包含数组的对象,因此您可以使用您已经拥有的所有知识。只是data.items
用来访问数组。
For example, to add another item to the array using dynamic values:
例如,要使用动态值向数组添加另一个项目:
// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);
回答by Siva Anand
Adding an object in a json array
在 json 数组中添加对象
var arrList = [];
var arr = {};
arr['worker_id'] = worker_id;
arr['worker_nm'] = worker_nm;
arrList.push(arr);
Removing an object from a json
从 json 中删除对象
It worker for me.
它对我有用。
arrList = $.grep(arrList, function (e) {
if(e.worker_id == worker_id) {
return false;
} else {
return true;
}
});
It returns an array without that object.
它返回一个没有该对象的数组。
Hope it helps.
希望能帮助到你。
回答by Spiny Norman
Well, it's just a javascript object, so you can manipulate data.items
just like you would an ordinary array. If you do:
好吧,它只是一个 javascript 对象,因此您可以data.items
像操作普通数组一样进行操作。如果你这样做:
data.items.pop();
your items
array will be 1 item shorter.
您的items
数组将缩短 1 个项目。
回答by Talha
Keep things simple :)
保持简单:)
var my_form_obj = {};
my_form_obj.name = "Captain America";
my_form_obj.weapon = "Shield";
Hope this helps!
希望这可以帮助!
回答by Kamil Kie?czewski
Try
尝试
data.items.pop();
data.items.push({id: "7", name: "Matrix", type: "adult"});
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"}
]};
data.items.pop();
data.items.push({id: "7", name: "Matrix", type: "adult"});
console.log(data);