gpt4 book ai didi

jquery - 从嵌套 json 数组 jquery 中删除对象(拼接)

转载 作者:行者123 更新时间:2023-12-01 03:35:51 26 4
gpt4 key购买 nike

我有这个 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"
}
]
}
]
}

我尝试从类别的标题列表中删除对象(项目)。为此,使用了 Javascript 中的 splice 函数。该过程运行良好,但仅适用于类别标题列表中的最后一个对象。当列表中间的对象被删除时,控制台中会出现一个奇怪的通知。无论如何,该对象都会从数组中删除。

代码如下所示:

$.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 is undefined

只有当想要删除非最后位置的对象时才会出现。知道为什么会出现此错误

最佳答案

跟进@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/

关于jquery - 从嵌套 json 数组 jquery 中删除对象(拼接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35128769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com