javascript 如何在Reactjs中创建具有不同标签和值的对象数组

fquxozlt  于 2023-02-21  发布在  Java
关注(0)|答案(3)|浏览(152)

我正在使用这个。state。student来响应显示(名称、学校、班级等)。我如何将“学校”显示更改为“学院”,而不替换API中“学校”的值。
由于我是新的代码,我尝试

'var student = [ {"name", "school", "class"}];'
'student[1] = "college";'

但是这只是替换了值。我只是想改变“学校”的显示,请帮助

g52tjvyc

g52tjvyc1#

检查我的代码,我创建了一个函数addToArray,它将接受object的参数,然后将其添加到students数组中,这将给予[{ name: "John Doe", school: "College", class: "A" }]的输出

let students = [];

addToArray = student => {
  students.push({
    name: student.name,
    school: student.school,
    class: student.class
  });
  console.log(students);
};

this.addToArray({
  name: "John Doe",
  school: "College",
  class: "A"
});
jk9hmnmh

jk9hmnmh2#

使用此函数创建具有不同键和值对对象数组,

var productArr = [];

productId = 1;
productName = 'Product Name';

productArr.push({ id: productId, name: productName });

希望对你有用。等待你的回复。谢谢!

owfi6suc

owfi6suc3#

你可以试试这个:

var student = [ {"name": "school", "class":"XYZ"}];
student = [...student,{"name":"college","class":"ABC"}]
console.log(student)

相关问题