我有一个数组
[{
"studentname": "abc",
"marks": "20"
},
{
"studentname": "abc2",
"marks": "20"
}
]
我想在studentname=abc的地方再加10个标记,那么怎么做呢
eg.10 30 + 20 =因此输出将是
[{
"studentname": "abc",
"marks": "30"
},
{
"studentname": "abc2",
"marks": "20"
}
]
const updatedArray = array.map(item => {
if (item.studentname === "abc") {
return {
studentname: "abc",
marks: parseInt(item.marks, 10) + 10
};
} else {
return item;
}
});
这是一种简洁的方法。
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)
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)
- 循环遍历对象数组
- 检查当前对象的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);