我试图从json数组中删除一段数据.例如,我有这个数组
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"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
假设我想通过点击按钮将产品从浴室类别中移除.我怎么会这样做?
我一直试图这样做无济于事:
jQuery(document).on('click', ".removeFav", function() {
favorites.favorites[1].items[1].splice();
}
Run Code Online (Sandbox Code Playgroud)
我收到的错误:
未捕获的TypeError:对象#没有方法'拼接'
Mac*_* Sz 17
要取消设置任何变量,请使用以下delete语句:
delete favorites.favorites[1].items[1]
Run Code Online (Sandbox Code Playgroud)
这是正确的方法,它会起作用,但如果您的目标是按顺序保留索引,那么使用该splice方法的方法就是:
favorites.favorites[1].items.splice(1,1);
Run Code Online (Sandbox Code Playgroud)
以上将从第一个索引(第一个参数)开始删除一个元素(第二个参数).
所以要明确:删除最后一个元素使用:
var arr = favorites.favorites[1].items;
arr.splice(arr.length - 1, 1);
Run Code Online (Sandbox Code Playgroud)
如果数组未设置或为空,您可以采取其他措施来保护代码:
var arr = favorites.favorites[1].items;
if ( arr && arr.length ) {
arr.splice(arr.length - 1, 1);
}
Run Code Online (Sandbox Code Playgroud)