如何在Angular 5应用中从JSON正确访问数组元素?

时间:2019-02-21 07:18:37

标签: arrays json angular

我具有以下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中访问数组元素吗?

2 个答案:

答案 0 :(得分: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 :(得分:0)

if(this.company)
     this.Company.trips.forEach(x => {
            console.log(x);
        });