Angular 在typescript中访问给定属性名称的数组
我有一个像这样的对象:Angular 在typescript中访问给定属性名称的数组,angular,typescript,Angular,Typescript,我有一个像这样的对象: let res = [{ stop: "stop1", students: [ "Maria", "Mario" ]}, {stop: "stop2", students: [ "Giovanni", "Giacomo" ] }]; 以及一个功能,用于检查学生是否已经出现在给定的公交车站: checkStudent(stopName: string, studentName: string): boolean {
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是否存在。我想知道是否有更好的方法。给定站点名称,我可以直接访问正确的学生数组吗?
我使用的是typescript,首先你的
res
对象声明不正确,它应该是数组,如下代码示例所示
要检查约束,您可以使用some
和includes
,如下例所示
如果需要对象,请使用过滤器
,而不是一些
let res=[{
停止:“停止1”,
学生:[
“玛丽亚”,
“马里奥”
]
}, {
停止:“停止2”,
学生:[
“乔瓦尼”,
“贾科莫”
]
}];
函数checkStudent(stopName,studentName){
返回res.some(x=>x.stop==stopName&&x.students.includes(studentName));
}
函数checkStudentAndReturnObject(stopName、studentName){
返回res.filter(x=>x.stop==stopName&&x.students.includes(studentName));
}
console.log(checkStudent(“stop1”、“Maria”);
log(checkStudentAndReturnObject(“stop1”、“Maria”)代码>给定停止名称,您无法真正“直接”访问正确的students数组,因为该数组不受停止名称的键控,但是您可以使用for循环执行此操作以保存您:
const targetStop = res.find(stopObject => stopObject.stop === stopName);
targetStop.students // <--- your array
const targetStop=res.find(stopObject=>stopObject.stop==stopName);
targetStop.students//请共享checkStudent函数内容您的res对象看起来不正常。它真的有两个同名的键吗students
和stop
?操作它是一个数组我会编辑我的问题我能直接访问正确的students数组吗?不,需要循环。但是您可以使用标准函数来完成这个循环,比如find()和some()。通过return res.filter(x=>x.stop==stopName&&x.students.includes(studentName))[0]禁止相同元素的出现是否更好代码>@Abdulrahman,我们不应该这样做,因为如果没有找到匹配的对象,那么它将返回未定义的。而不是空数组。谢谢,这正是我要找的。我将检查一些和筛选器之间的差异:)