Mina Gabriel
Mina Gabriel

Reputation: 25080

How to remove object in object array : jquery?

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

Upvotes: 0

Views: 2501

Answers (1)

Alnitak
Alnitak

Reputation: 339786

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;
        }
    }
});

Upvotes: 5

Related Questions