相关疑难解决方法(0)

如何更新数组值javascript?

我在javacsript中有一个由3个keyValue构造函数对象组成的数组:

  function keyValue(key, value){
    this.Key = key;
    this.Value = value;
  };

  var array = [];
  array.push(new keyValue("a","1"),new keyValue("b","2"),new keyValue("c","3"));
Run Code Online (Sandbox Code Playgroud)

我还有一个函数'Update',它接受keyValue object as parameter并更新数组中该对象的值:

  function Update(keyValue, newKey, newValue)
  {
    //Now my question comes here, i got keyValue object here which i have to 
    //update in the array i know 1 way to do this 

    var index = array.indexOf(keyValue);
    array[index].Key = newKey;
    array[index].Value = newValue; 
  }
Run Code Online (Sandbox Code Playgroud)

但是如果有的话,我想要一个更好的方法来做到这一点.

javascript jquery

7
推荐指数
3
解决办法
10万
查看次数

Javascript通过对象的属性更新数组对象

我有一组 person 对象,我想更新一个对象。

persons: [{
    id: '1',
    name: 'John',
    age: 12
    }, {
    id: '2',
    name: 'Tom',
    age: 13
    }, {
    id: '3',
    name: 'David',
    age: 14
}]
Run Code Online (Sandbox Code Playgroud)

我的功能是:

function updatePersonsWith(id, propName, value) {
   this.persons.???
}
Run Code Online (Sandbox Code Playgroud)

传递的参数是id我想更新的人,propName是的属性person的对象,可以是idname或者agevalue是我想,以取代的价值。

我想通过它的 id 找到一个对象并只更新数组的这个对象。

updatePersonsWith(2, age, 16)
Run Code Online (Sandbox Code Playgroud)

结果将是:

persons: [{
    id: '1',
    name: 'John',
    age: 12
    }, {
    id: '2',
    name: 'Tom',
    age: 16
    }, {
    id: '3',
    name: 'David', …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 lodash

1
推荐指数
1
解决办法
8445
查看次数

标签 统计

javascript ×2

ecmascript-6 ×1

jquery ×1

lodash ×1