0

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

3
  • Change it to x.splice - this is the array element. Commented Aug 15, 2012 at 12:48
  • are you just trying to remove that object from y.info, i.e. leaving {name: y, age: 15 }, or do want to remove the entire object y from the array x ? Commented Aug 15, 2012 at 12:51
  • no just leaving {name: y, age: 15 } Commented Aug 15, 2012 at 12:54

1 Answer 1

5

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;
        }
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

i tried your answer and it give me this error Uncaught TypeError: Cannot read property 'name' of undefined don't know why jsFiddle
@MinaGabriel because after splicing the array in next iteration there is no object or name property at that index.
i don't understand ? we removed {name:'x' ,age:58} from x.info i should now have y.info = [{name:'y' , age:15}] i don't even have array x
@MinaGabriel you do have an array x. However this code still doesn't work because it modifies the array while it's being iterated over.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.