【发布时间】:2021-10-18 01:44:23
【问题描述】:
有一些json格式的元素列表,如下所示:
[{
'id': 0,
"name": "Category name1",
"services": [{
"id": 0,
"name": "Product name1"
}, {
"id": 1,
"name": "Product name2"
}]
},
{
'id': 1,
'name': "Category name2",
"services": [{
"id": 0,
"name": "Product name1"
}, {
"id": 1,
"name": "Product name2"
}]
}
]
我试图只从第一个类别中获取整个“服务”数组。有条件地,我试图得到它如下:
this.class = this.http.get('/assets/products.json');
this.class.forEach(element => {
if (element.id == ID) //The ID is obtained when calling the function in which this code is executed
{
console.log(element.services);
}
}
但是,这完全没有给我任何东西,并且“未定义”输出到控制台,但是,在站点 https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach 上使用相同的数组和相同的条件下,它(foreach 和 console.log)输出我需要的一切。
//The same foreach only on the mozilla website
array1.forEach(item => {
if(item.id==1){ //1 вместо ID
console.log(item.services);
}});
输出到控制台:数组 [Object { id: 0, name: "Product name1"}, Object { id: 1, name: "Product name2"}]。
附:我真的不需要控制台中的这个产品列表,我正在尝试传递一个变量,但是由于 undefined 被传递给变量以及控制台,我无法使用该变量并将其调用在页面上展示产品。所有这些都在 typescript angular 项目中使用。
【问题讨论】:
-
也许“ID”未定义。请检查“ID”是否正确传递?
-
是的,ID 未定义。但是“如果”是有效的,如果我发送 this.class.forEach(element=>{ if(element.id==ID){ console.log(element) //without .services } }),它会输出所有类和产品表示正在读取 ID
-
this.rout.paramMap.subscribe(params=>{ console.log(this.classID = params.get('class.id')) } 如果在地址栏,在我的例子中是 1,但是将它传递给上面未定义问题中描述的函数
标签: arrays json angular typescript