从json数组中删除数据 [英] Delete data from json array
问题描述
我试图从json数组中删除一段数据。例如,我有这个数组
I am trying to remove a piece of a data from a json array. For example I have this array
var favorites = {
"userID": "12345678",
"favorites": [
{ "name" : "My Favorites",
"id" : "87654321",
"items":
[
{
"productID": "11234567",
"added": "TIMESTAMP",
"title": "Project",
"type": "Weekend Project",
"imageURL": "1"
},
{
"productID": "11223456",
"added": "TIMESTAMP",
"title": "Bathroom",
"type": "Weekend Project",
"imageURL": "2"
},
{
"productID": "11223345",
"added": "TIMESTAMP",
"title": "Curves",
"type": "Collections",
"imageURL": "3"
}
]
},
{ "name" : "Bathroom",
"id" : "87654323",
"items":
[
{
"productID": "11122224",
"added": "TIMESTAMP",
"title": "Project",
"type": "Weekend Project",
"imageURL": "1"
},
{
"productID": "11122222",
"added": "TIMESTAMP",
"title": "Room",
"type": "Weekend Project",
"imageURL": "2"
},
{
"productID": "11112222",
"added": "TIMESTAMP",
"title": "Strais",
"type": "Collections",
"imageURL": "3"
},
{
"productID": "11111222",
"added": "TIMESTAMP",
"title": "Door",
"type": "Collections",
"imageURL": "4"
}
]
}
]
}
说我想点击一下浴室类别中的产品一个按钮。我将如何实现这一目标?
Say I wanted to remove the a product out of the bathroom category on the click of a button. How would I acheive this?
我一直试图这样做无济于事:
I have been trying this to no avail:
jQuery(document).on('click', ".removeFav", function() {
favorites.favorites[1].items[1].splice();
}
错误我收到:
Uncaught TypeError:Object#没有方法'splice'
Uncaught TypeError: Object # has no method 'splice'
推荐答案
To取消设置任何变量使用 delete
语句:
To unset any variable use the delete
statement:
delete favorites.favorites[1].items[1]
这是正确的方法,它会起作用,但如果你的目标是按顺序保存索引,然后使用 splice
方法的方法:
This is correct way, and it will work, but if your goal is to preserve indexes in order, then your way with the splice
method is the way to go:
favorites.favorites[1].items.splice(1,1);
上面将从第一个索引(第一个参数)开始删除一个元素(第二个参数)。
The above will remove one element (second parameter) starting at 1st index (first parameter).
所以要明确:到r emove最后一个元素使用:
So to be clear: to remove the last element use this:
var arr = favorites.favorites[1].items;
arr.splice(arr.length - 1, 1);
如果数组未设置或为空,您可以采取其他措施来保护代码:
You can take additional measures to protect the code in case the array is not set or empty:
var arr = favorites.favorites[1].items;
if ( arr && arr.length ) {
arr.splice(arr.length - 1, 1);
}
这篇关于从json数组中删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!