【问题标题】:How to access array element correctly from JSON in Angular 5 app?如何从 Angular 5 应用程序中的 JSON 正确访问数组元素?
【发布时间】:2019-07-15 00:38:50
【问题描述】:

我有以下 JSON 定义:

export class Company {
  name: string;
  trips : Trip[] = [];
}

我可以使用以下命令在控制台中查看行程:

console.log(this.company);  

但我无法访问数组元素(行程),我试过了 以下:

for(let i = 0; i < this.company.trips.length; i++){
        console.log(this.company.trips[i]);      
  }  

当我在日志中显示公司时,我会尽你所能 见下文:

{id: 1}
name: "Sample"
trips: {id: 1, r: "ABC"}
id: 1

知道如何在 Angular 中访问数组元素吗?

【问题讨论】:

  • 这个变量叫做trip ...不是trips。更改班级中的名称。行程:行程[]。也当控制台。像这样记录它只会显示“对象”,如果你不指定trips的属性
  • 这是一个错字,我将问题更新为“trips”。
  • 我很好奇,他是如何编写代码的。它会正确抛出错误。
  • 是的。它会。但我猜他是打字而不是复制。
  • 在 .ts 中,数组索引从 0 开始,因此对于 (let i=0;i

标签: arrays json angular


【解决方案1】:

使用Object.keys()forEach() 的组合可以让您以类似于数组的方式遍历对象。

说明

const x = {hello: "hi"};  
console.log(Object.keys(x)); // will return array looking like 

// [hello] which you can run a for each on.

Object.keys(x).forEach(data => {
    console.log(x[data]); // will return `hi`
});

解决方案

const trips = {id: 1, r: "ABC"}; // const trips = this.company.trips

if (trips) // check the value exists here 
  {
    Object.keys(trips).forEach((data) => {
    console.log(trips[data]);
  });
}

【讨论】:

  • 您的解决方案有效,我现在可以在日志中看到:1 ABC 但由于某种原因它显示了多次,比如 30 次。
  • 请确保您只在我认为您遇到问题时才调用此函数。
  • 您的解决方案有效,所以我将解决这个问题并为副本打开一个新问题。
【解决方案2】:
if(this.company)
     this.Company.trips.forEach(x => {
            console.log(x);
        });

【讨论】:

  • 我得到:错误类型错误:this.company.trips.forEach 不是函数
  • 是的,正如您在我的问题中看到的那样。
  • 如果是数组,你可能不会得到 forEach is not an function 错误。更好地显示您的示例响应。
猜你喜欢
  • 2019-03-27
  • 1970-01-01
  • 2019-07-15
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
相关资源
最近更新 更多