简体   繁体   English

更改数组中的特定对象

[英]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". 例如,从上面显示的数组开始,当name等于“nameToChange”时,我希望将value更改为“newValue”。

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

PS. 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"> . 要创建初始数组,我使用的是jQuery的serializeArray() ,我不希望更改<input name="nameToChange"> I suppose I can change its value, use serialArray() , and then change it back, but this sounds more complicated than necessary. 我想我可以改变它的值,使用serialArray() ,然后将其更改回来,但这听起来比必要的复杂。

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. 您将无法使用本机'indexOf'执行相同的操作,因为要比较对象。

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; 这是2013年; skip all the messy for loops and use forEach . 跳过所有凌乱的for循环并使用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: 由于您使用的是jQuery,因此可以使用:

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

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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