i'm confused i was trying to remove object in object array using jquery here is my code , jsFiddle
var x = new Array() ;
var y = {} ;
y.name = 'myName' ;
y.age = 28 ;
y.phone = 27895556 ;
y.info = [{name:'x' ,age:58} ,{name:'y' , age:15}]
x.push(y) ;
$.each(x , function(index,value) {
$.each(value.info , function(i,v){
if(v.name == 'x'){
this.splice(i,1) ;
}
});
});
i was trying to tell the if condition to remove the object with v.name = 'x' but i get this error Uncaught TypeError: Object # has no method 'splice'
UPDATE i need to have something like : y.info = [{name:'x' ,age:58} ,{name:'y' , age:15}] after splice()
any idea what i'm doing wrong Thanks
1 Answer 1
If you're just trying to remove the inner array element that contains the value {name: 'x'} then the array you want to splice is the value.info of the outer loop:
$.each(x, function(index, value) {
$.each(value.info, function(i, v) {
if (v.name === 'x') {
value.info.splice(i, 1) ;
}
});
});
However this code suffers from the problem that you shouldn't modify an array's length while iterating over it with $.each. This alternate code fixes that problem:
$.each(x, function(index, value) {
var info = value.info;
for (var i = 0; i < info.length; ) {
if (info[i].name === 'x') {
info.splice(i, 1);
} else {
++i;
}
}
});
4 Comments
Uncaught TypeError: Cannot read property 'name' of undefined don't know why jsFiddle {name:'x' ,age:58} from x.info i should now have y.info = [{name:'y' , age:15}] i don't even have array xx. However this code still doesn't work because it modifies the array while it's being iterated over.
x.splice-thisis the array element.y.info, i.e. leaving{name: y, age: 15 }, or do want to remove the entire objectyfrom the arrayx?{name: y, age: 15 }