Mina Gabriel
Mina Gabriel

Reputation: 25080

How do I change the element value in an object array

How can I change the value of an element in object array? My example below removes one object from an array and then change the element (number) in the rest of the object - the removing part works fine but the other part doesn't-

I have a jsFiddle

code :

var x =[
    {name : 'myname' , number : '10' , color:'green'},
    {name : 'yourname' , number : '15' , color:'blue'}
]; 

$.each(x , function(index ,value) {
    if(value.number == '10'){
        x.splice(index , 1) ; 
    } 
    else {
        x[i].number = '20' ; 
    }
    console.log(x) ; 
});​

Upvotes: 1

Views: 132

Answers (4)

Nishu Tayal
Nishu Tayal

Reputation: 20830

Try this.

 var x =[{name : 'myname' , number : '10' , color:'green'},
       {name : 'yourname' , number : '15' , color:'blue'}] ; 

 $(x) . each(function(index ,value){
    if(value.number != undefined && value.number == '10'){
        x.splice(index , 1) ; 
    }else {
       if(value.number != undefined){
           value.number= '20' ; 
       }
    }
    console.log(x) ; 
});​

Here is demo

Use undefined check for that object index.

Upvotes: 0

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

You can use .map() to build a new array like this

var x =[{name : 'myname' , number : '10' , color:'green'},
  {name : 'yourname' , number : '15' , color:'blue'}] ; 

var newX = $.map(x , function(obj ,index){
    if(obj.name == 'yourname'){
        return null;
    }else{
       obj.number = '20';
       return obj; 
    }
});

console.log(newX);

Demo: http://jsfiddle.net/joycse06/C3d9T/3/

Upvotes: 2

xcopy
xcopy

Reputation: 2288

You need to decrement the loop counter when removing an element of the array your are looping. I am not sure if this can be easily done with jQuery's each(). You can just use a normal for loop:

for(var i = 0; i < x.length; i++) {
    var value = x[i];
    if(value.number == '10') {
        x.splice(i, 1); 
        i--;
    }
    else {
        value.number = '20'; 
    }
    console.log(x); 
}

Here is a demo - http://jsfiddle.net/bFYj7/

Upvotes: 0

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

Looks like you can use $.map() to do this for you.

var new_array = $.map(x, function (el) {

    if (el.number === '10') {
        // remove this
        return null;
    } else {
        // transform into something else
        el.number = '20';
        return el;
    }

});

Note that this creates a new array. You can overwrite your old array by assigning the return to the old variable:

x = $.map(x, function (el) { });

Upvotes: 0

Related Questions