代码之家  ›  专栏  ›  技术社区  ›  Jojo Narte

在遵循流规则的同时通过匹配键合并两个对象

  •  1
  • Jojo Narte  · 技术社区  · 6 年前

    假设我们给出了以下数据:

    subjects = {
      student1: ['Math', 'Science'],
      student2: ['Math', 'Physics', 'English'],
    };
    
    students = {
     student1: {
        // other data
        subjectsList: [],
     },
     student2: {
        // other data
        subjectsList: [],
     },
    };
    

    const merge = (subjects: Object, students: Object) => {
        Object.keys(subjects).forEach((id: Object) => {
          const subjectsList = subjects[id];
          const student = students[id];
    
          if (student) {
            const updatedStudent = {
              ...student,
              subjectsList,
            };
    
            students[id] = updatedStudent;
          }
        });
    
        return students;
      };
    

    这将导致流错误:

    Cannot access the computed property using object type [1].
    
    app/reducers/subjects.reducer.js:42:32
    42|           const student = students[id];
                                       ^^
    
    References:
    app/reducers/subjects.reducer.js:40:48
    40|         Object.keys(subjects).forEach((id: Object) => {
                ^^^^^^ [1]
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Romil    6 年前

    Object.keys(subjects).forEach((id: Object)

    这个 id .forEach((id) => 不是一个 ,但是 字符串

    const merge = (subjects, students) => {
        Object.keys(subjects).forEach((id) => {
          const subjectsList = subjects[id];
          const student = students[id];
    
          if (stand) {
            const updatedStudent = {
              ...student,
              subjectsList,
            };
    
            students[id] = updatedStudent;
          }
        });
    
        return students;
      };
    

    我想这会管用的。