Skip to content Skip to sidebar Skip to footer

Alter Array Object Using Loop

var arr = [{id:1,'name':'John'},{id:2,'name':'James'}] $.each(arr, function(){ if(this.id == 1){ //change john to Johnathan } }); without using key, is it possible to alter array

Solution 1:

Sure you can do that by converting the object to a string if you are looking for a hack. What is it that you are looking to do?

var arr = [{id:1,"name":"John"},{id:2,"name":"James"}]

$.each(arr, function(i){
     if(this.id == 1){
         arr[i] = JSON.parse(JSON.stringify(this).replace("John", "Johnathan"))
     }
});

Solution 2:

You do like this in the loop:

var arr = [{id:1,"name":"John"},{id:2,"name":"James"}]

$.each(arr, function(){
if(this.id == 1){
this.name = 'Johnathan';
//change john to Johnathan
}
});

Solution 3:

The only way I can think of would change all "John" values to "Johnson" in all properties without explicitly using a property name. You can loop all properties on an object.

for (var i = 0; i < arr.length; i++) {
    for (var prop in object) {
        if (object.hasOwnProperty(prop)) {
            if (arr[i][prop] === 'John') {
                arr[i][prop] = 'Johnson';
            }
        }
    }
}

This probably won't work for you, but it's the only way to grab a value on an object without using the property name explicitly.


Solution 4:

then i think you need to replace whole array's object with having id == 1

here is what i tried

for(var i = 1;i<arr.length;i++){
if(this.arr[i].id == 1){
 
  this.arr[1] = {'id':'1','name':'Johnathan'};

}

Post a Comment for "Alter Array Object Using Loop"