简体   繁体   中英

Change a particular object in an array

Starting with an array of objects:

var array=[
    {name:"name1",value:"value1"},
    {name:"nameToChange",value:"oldValue"},
    {name:"name3",value:"value3"}
];

How do change the value of a given property of one of the objects when another given property in the object is set to a given value?

For instance, starting with my array shown above, I wish to change value to "newValue" when name is equal to "nameToChange".

var array=[
    {name:"name1",value:"value1"},
    {name:"nameToChange",value:"newValue"},
    {name:"name3",value:"value3"}
];

PS. To create the initial array, I am using jQuery's serializeArray() , and I do not wish to change the value of <input name="nameToChange"> . I suppose I can change its value, use serialArray() , and then change it back, but this sounds more complicated than necessary.

The easiest way is to iterate over this array:

var i = arr.length;
while (i--) {
  if (arr[i].name === 'nameToChange') {
    arr[i].value = 'newValue';
    break; 
  } 
}

You won't be able to do the same stuff with native 'indexOf', as objects are to be compared.

for (var i = 0; i < array.length; i++) {
    if (array[i].name == 'nameToChange') {
        array[i].value = 'value';
        break;
    }
}

fiddle Demo

You need to go through all the elements and search for the required one and then replace with the value.

for(var i = 0; i < array.length; i++){
    if(array[i]["name"] == str) {
        array[i]["value"] = newValue;
        break;
    }
}

It's 2013; skip all the messy for loops and use forEach . It's much simpler and semantically cleaner:

array.forEach(function (e) {
  if (e.name == 'nameToChange')
    e.value = 'newValue';
})

Since you are using jQuery, you could use this:

$.each(array, function () {
    if(this.name == 'nameToChange') this.value = 'value';
});

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM