我有这个JSON对象:
{
"Videotheck":[
{
"Category":"Comedy",
"Title_Liste":[
{
"Title":"Millers",
"Year":"2014"
},
{
"Title":"Yogi",
"Year":"2012"
}
]
},
{
"Category":"Accion",
"Title_Liste":[
{
"Title":"Rodulf",
"Year":"2014"
},
{
"Title":"Matrix",
"Year":"2000"
}
]
}
]
}
我尝试从类别的标题列表中删除一个Object(项目)。为此,使用来自Javascript的函数拼接。该过程运行良好,但仅适用于类别标题列表中的最后一个对象。当删除列表中间的对象时,控制台中会出现奇怪的通知。无论如何都要从数组中删除该对象。
代码如下所示:
$.each(VT.Videotheck,function(k,v){
if(v.Category == 'Comedy'){
$.each(v.Title_Liste,function(b,z){
if(z.Title == 'Millers'){
v.Title_Liste.splice(b,1);
}
});
}
});
控制台中的通知是:
TypeError:z未定义
仅在想要删除没有最后一次的对象时出现。知道为什么会出现这个错误
答案 0 :(得分:2)
跟进@ Tokn的回答。以下是过滤阵列的方法:
var VT = {
"Videotheck": [{
"Category": "Comedy",
"Title_Liste": [{
"Title": "Millers",
"Year": "2014"
}, {
"Title": "Yogi",
"Year": "2012"
}]
}, {
"Category": "Accion",
"Title_Liste": [{
"Title": "Rodulf",
"Year": "2014"
}, {
"Title": "Matrix",
"Year": "2000"
}]
}]
}
var VT2 = {
"Videotheck": [{
"Category": "Comedy",
"Title_Liste": [{
"Title": "Millers",
"Year": "2014"
}, {
"Title": "Yogi",
"Year": "2012"
}]
}, {
"Category": "Accion",
"Title_Liste": [{
"Title": "Rodulf",
"Year": "2014"
}, {
"Title": "Matrix",
"Year": "2000"
}]
}]
}
// Example #1: Using native loops is always better..
for ( var i = 0, l = VT.Videotheck.length; i < l; i++ ) {
var property = VT.Videotheck[i];
if ( property.Category === "Comedy" ) {
var dirtyArray = property.Title_Liste;
var filteredArray = [],
ii = 0,
ll = dirtyArray.length;
for (; ii < ll; ii++) {
var movie = dirtyArray[ii];
if ( movie.Title !== "Millers" ) {
filteredArray.push( movie );
}
}
property.Title_Liste = filteredArray;
}
}
// Example #2: es5 methods / loops
VT2.Videotheck.forEach( function( element ) {
if ( element.Category === "Comedy" ) {
element.Title_Liste = element.Title_Liste.filter( function( movie ) {
return movie.Title !== "Millers";
} )
}
} );
jsFiddle:https://jsfiddle.net/yj4a1rsy/
答案 1 :(得分:1)
我认为,当您在$ .each循环中仍在循环播放时,您正在从阵列中删除项目。
您需要存储对要删除的项目的引用,并在完成循环后拼接它们。