代码之家  ›  专栏  ›  技术社区  ›  CodeRonin

在typescript中访问给定属性名的数组

  •  2
  • CodeRonin  · 技术社区  · 7 年前

    我有一个像这样的物体:

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

    以及一个功能,用于检查学生是否已经出现在给定的公共汽车站:

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

    到目前为止,我所做的是遍历res对象,检查每个stopName,直到其中一个与“stopName”参数匹配,然后遍历students数组以检查student是否存在。我想知道有没有更好的办法。我可以直接访问给定站点名称的正确学生数组吗? 我在用打字机

    2 回复  |  直到 7 年前
        1
  •  5
  •   Karan    7 年前

    你的第一件事 res 对象的声明不正确,它应该是如下代码示例所示的数组。

    为了检查你的约束,你可以使用 some 到和 includes 如下例。

    如果需要对象,请使用 filter 而不是 一些 .

    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"));
        2
  •  0
  •   Melbourne2991    7 年前

    不能“直接”访问给定停止名的右students数组,因为该数组不受停止名的键控,但是可以使用for循环来保存:

    const targetStop = res.find(stopObject => stopObject.stop === stopName);
    
    targetStop.students // <--- your array
    
    推荐文章