如何在JavaScript数组中添加/替换内部对象

时间:2017-08-09 10:40:41

标签: javascript arrays json ecmascript-6

我有一个

形式的JavaScript数组
const Rooms = [{
        name:"Science",
        students:[
            {user:"Tom",emotion:"Happy"},
            {user:"Marry",emotion:"Angry"},
            {user:"Adam",emotion:"Happy"}]
    },{
        name:"Maths",
        students:[
        {user:"Stewie",emotion:"Angry"},
            {user:"Cleavland",emotion:"Angry"},
            {user:"Meg",emotion:"Happy"},
            {user:"Peter",emotion:"Angry"},
            {user:"Chris",emotion:"Happy"}]
    },{
        name:"History",
        students:[
            {user:"Monica",emotion:"Angry"},
            {user:"Chandler",emotion:"Happy"},
            {user:"Joe",emotion:"Happy"},
            {user:"Ross",emotion:"Angry"}]
    }];

我需要按姓名找房间,并在需要时由学生添加/替换。这意味着我应该能够找到房间(数学)并添加/更新学生。如果学生已经在那里,那么应该改变它的情绪。

这是我尝试过的代码,但它并没有取代现有的学生。

Rooms.forEach((e)=>{if(e.name === "Science"){
    e.students.push({user:"Tom",emotion:"Surprised"});
}});

如何搜索特定的json并更改现有学生或添加新学生数据(如果学生不在场)?

1 个答案:

答案 0 :(得分:0)

在学生数组中使用find:

例如,找到" Tom"并更新它:

Rooms.forEach((e)=>{
  if(e.name === "Science"){
   const tom = e.students.find((student) => student.user === "Tom");
   if (!tom)       
      e.students.push({user:"Tom",emotion:"Surprised"});
   else
      tom.emotion = "Surprised";
  }
});

注意:您也可能使用find查找房间而不是使用forEach:

const e = Rooms.find((room) => room.name === "Science");
if (e) {
  const tom = e.students.find((student) => student.user === "Tom");
  if (!tom)       
     e.students.push({user:"Tom",emotion:"Surprised"});
  else
     tom.emotion = "Surprised";
  }
}