0

I have the following JSON definition:

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

I am able to see the trips in the console using:

console.log(this.company);  

But I am not able to access the array elements (trip), I've tried the following:

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

When I display the company to the log I'm getting the trip as you can see below:

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

Any idea how to access array elements in Angular thanks?

7
  • 1
    the variable is called trip ... not trips. change the name in the class. trips: Trip[]. Also when console. logging like this it will just show "Object" if you dont specify a property of trips Commented Feb 21, 2019 at 7:24
  • 1
    it was a typo, I update the question to "trips" as it should be. Commented Feb 21, 2019 at 7:27
  • I am curious, how he wrote that code. It will throw error right. Commented Feb 21, 2019 at 7:27
  • yes. it would. but i guess he typed it instead of copying. Commented Feb 21, 2019 at 7:28
  • in .ts the array index begings by 0, so for (let i=0;i<this.company.trips.length;i++) -use "let, not var", and begind by 0-. By the way you must sure this.company.trips are not null. You can use trips : Trip[]=[] Commented Feb 21, 2019 at 7:33

2 Answers 2

1

Using a combination of Object.keys() and forEach() will let you iterate through the the object in a similar fashion to an array.

explination

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`
});

Solution

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]);
  });
}

Sign up to request clarification or add additional context in comments.

3 Comments

Your solution work, I am able to see in the log now: 1 ABC but from some reason it show multiple times, something like 30 times.
Be sure that you only call this function once i would imagine that would be where you are getting an issue.
Your solution works so I'm going to solve this question and open a new one for the duplicate.
0
if(this.company)
     this.Company.trips.forEach(x => {
            console.log(x);
        });

3 Comments

I ma getting: ERROR TypeError: this.company.trips.forEach is not a function
Yes it is as you can see in my question.
if it is array, you might not get forEach is not an function error. better show your sample response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.