【问题标题】:I need to get a nested element in a json array我需要在 json 数组中获取嵌套元素
【发布时间】: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


【解决方案1】:

HttpClient 方法如 get 返回 observables,您需要订阅这些数据才能执行请求。在您的情况下,class 属性仅持有对调用this.http.get 返回的可观察对象的引用。尝试订阅 observable 并使用结果来提取您需要的数据。

this.http.get<any[]>('/assets/products.json').subscribe((data) => {
  this.class = data;
  this.class.forEach((element) => {
    if (element.id == ID) {
      console.log(element.services);
    }
  });
});

【讨论】:

  • 我认为这行得通,但 ID 未定义,因此显然“如果”不起作用,但是,如果您输入一个整数(例如,0 或 1),则所有内容都按应有的方式输出.
  • 我的错:我将 ID 值传递给了 ngOnInit,而不是构造函数。我修复了这个错误,一切正常。谢谢你和所有回答的人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
相关资源
最近更新 更多