如何在数组中用新值更新旧值[React native]

2hh7jdfx  于 2022-12-19  发布在  React
关注(0)|答案(4)|浏览(140)

我有数组

[{
        "studentname": "abc",
        "marks": "20"
    },
    {
        "studentname": "abc2",
        "marks": "20"
    }
]

我想在studentname=abc的地方再加10个分数,怎么做呢
例如10 +20=30,因此输出将为

[{
        "studentname": "abc",
        "marks": "30"
    },
    {
        "studentname": "abc2",
        "marks": "20"
    }
]
s4n0splo

s4n0splo1#

const updatedArray = array.map(item => {
  if (item.studentname === "abc") {
    return {
      studentname: "abc",
      marks: parseInt(item.marks, 10) + 10
    };
  } else {
    return item;
  }
});
kuhbmx9i

kuhbmx9i2#

这是一个干净的方法。

const x= [{
        "studentname": "abc",
        "marks": "20"
    },
    {
        "studentname": "abc2",
        "marks": "20"
    }
]

x.forEach(function(obj) {
    if (obj.studentname === 'abc') {
        obj.marks = Number(obj.marks) + 10
    }
});

console.log(x)
tag5nh1u

tag5nh1u3#

const array= [{
        "studentname": "abc",
        "marks": "20"
    },
    {
        "studentname": "abc2",
        "marks": "20"
    }
]

array.map((item,index)=> {
    if (item.studentname == 'abc') {
        item.marks = Number(item.marks) + 10
    }
});

console.log("Your Updated Array Here:->",array)
lo8azlld

lo8azlld4#

  • 循环遍历对象数组
  • 检查当前对象的studentname属性是否等于abc
  • 如果是,则将当前对象的marks属性加10
  • 循环结束后,将使用修改后的对象更新数组
const arr = [{"studentname": "abc", "marks": "20"},    
       {"studentname": "abc2","marks": "20" }];

for (let i = 0; i < arr.length; i++) {
  if (arr[i].studentname === "abc") {
        arr[i].marks = parseInt(arr[i].marks) + 10;
    }
}

console.log(arr);

相关问题