遵循Flow规则时通过匹配键合并两个对象

时间:2018-09-12 03:37:49

标签: javascript

我创建了一个如下所示的函数,该函数应该将数组值附加到第一个对象中。

假设我们在下面提供了数据:

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]

0 个答案:

没有答案