在打字稿中访问给定属性名称的数组

GJC*_*ode 2 typescript angular

我有一个看起来像这样的对象:

let res = [{
  stop: "stop1",
  students: [
     "Maria",
     "Mario"
  ]},
 {stop: "stop2",
 students: [
   "Giovanni",
   "Giacomo"
 ]
}];
Run Code Online (Sandbox Code Playgroud)

和一个用于检查学生是否已在给定的巴士站出现的函数:

checkStudent(stopName: string, studentName: string): boolean {
   // iterate over res and check if students is present
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我所做的是遍历res对象,检查每个stopName直到其中一个与'stopName'参数匹配,然后遍历Student数组以检查是否存在Student。我想知道是否有更好的方法可以做到这一点。给定停止名称后,我可以直接访问合适的学生数组吗?我正在使用打字稿

Kar*_*ran 5

首先,您的res对象声明不正确,它应为数组,如下面的代码示例所示。

并检查您的约束,您可以使用someincludes为下面的例子。

如果您想要对象,请使用filter代替some

let res = [{
  stop: "stop1",
  students: [
    "Maria",
    "Mario"
  ]
}, {
  stop: "stop2",
  students: [
    "Giovanni",
    "Giacomo"
  ]
}];

function checkStudent(stopName, studentName) {
  return res.some(x => x.stop == stopName && x.students.includes(studentName));
}

function checkStudentAndReturnObject(stopName, studentName) {
  return res.filter(x => x.stop == stopName && x.students.includes(studentName));
}

console.log(checkStudent("stop1", "Maria"));
console.log(checkStudentAndReturnObject("stop1", "Maria"));
Run Code Online (Sandbox Code Playgroud)