JavaScript angular 4 fetching nested json

How can I access nested json? I have the following file:

{
    "user1": {
        "name": "john",
        "surname": "johnsson"
    },
    "user2": {
        "name": "Jacob",
        "surname": "Jacobsson"
    }
}

and so on. I need to make a table from this JSON data with fields name and surname with. How can I do this? I wrote the following code: users.service.ts

export class UsersService {
    private _url: string = '../assets/users.json';

    constructor(private _http: Http) {
    }

    getUsers() {
        return this._http.get(this._url).map((response: Response) =>
            response.json());
    }
}

and the users.component

export class UsersComponent implements OnInit {
    users = [];

    constructor(private _usersService: UsersService) {
    }

    ngOnInit() {
        this._usersService.getUsers().subscribe(resUsersData => this.users = resUsersData);
        console.log(this.users);
    }
}

then I just want to see my result using {{users}} in users.component.html but I see just [object Object]. So I obviously can't access anything else and getting the error.

Answer:1

The first thing you want to do is flatten your JSON data file:

[{
    "name": "John",
    "surname": "Johnsson"
}, {
    "name": "Jacob",
    "surname": "Jacobsson"
}]

You have named the file users.json, so you've already described that it will contain an array of user objects, which means there's no need to carry that level of hierarchy again in the file (user1, user2), in fact that makes them harder to get at. Your users file should be a single level array of objects, each with a name and surname property.

Notice also that the entire JSON block is wrapped as an array [{ }].

Second, your service:

export class UsersService {
    private _url: string = '../assets/users.json';

    constructor(private _http: Http) {
    }

    getUsers(): Observable<Response> {
        return this._http.get(this._url)
               .map(response => response.json())
    }
}

I make sure I type everything I can, as it makes it clearer when reading the code what types are expected, and the IDE can catch type mismatches for you, which makes debugging easier.

Then the component:

export class UsersComponent implements OnInit {
users: any;

constructor(private _usersService: UsersService) {
}

    ngOnInit() {
        this._usersService.getUsers()
            .subscribe(response => {
                this.users = response;
                console.log('Returned Users:', this.users);
        });
    }

If you console.log this.users outside of the subscription, then the console statement will execute before the service has resolved the data, and you'll get 'undefined', even though the data has come back, it's just been assigned to your variable after you logged it out. Always, with subscriptions, log out your data in the .subscribe block.

Now what you should have is this.users which contains an array of 2 user objects, each with a name and surname property, and you can iterate over those in the template with an *ngFor

  <ul>
    <li *ngFor="let user of users">{{user.name}}, {{user.surname}}</li>
  </ul>
Answer:2
your data format should be

   {
    "user": [{
        "name": "john",
        "surname": "johnsson"
    },{
        "name":"aish",
         "surname":"johnshon"
      }]
}

then you can use foreach to access all result

Answer:3

In ckeditor, instead of styles, I want to have classes for all styles. So I have used the following configuration. config.coreStyles_bold = { element: 'span', attributes: { 'class': ...

In ckeditor, instead of styles, I want to have classes for all styles. So I have used the following configuration. config.coreStyles_bold = { element: 'span', attributes: { 'class': ...

I am new to react-native. I am trying to use async/await but it doesn't wait for other function to return response and alert immediately it will not wait 4 seconds. Here is my code Please help me. ...

I am new to react-native. I am trying to use async/await but it doesn't wait for other function to return response and alert immediately it will not wait 4 seconds. Here is my code Please help me. ...

  1. react native asyncstorage
  2. react native asyncstorage example
  3. react native async
  4. react native async function
  5. react native asyncstorage best practices
  6. react native asyncstorage array
  7. react native asyncstorage getitem
  8. react native async render
  9. react native asyncstorage login example
  10. react native asyncstorage multiset example
  11. react native asyncstorage not working
  12. react native asyncstorage clear
  13. react native asyncstorage setitem
  14. react native asyncstorage save object
  15. react-native-async-storage npm
  16. react native async componentdidmount
  17. react native asyncstorage removeitem
  18. react native asyncstorage redux
  19. react native asyncstorage limit
  20. react native asyncstorage save array

I am new to nodejs and i need to divide an array which contain dates on x-axis and its points on y axis and trying to draw a graph using an array to store data for x and y axis to do that i am doing ...

I am new to nodejs and i need to divide an array which contain dates on x-axis and its points on y axis and trying to draw a graph using an array to store data for x and y axis to do that i am doing ...

  1. divide array into equal parts
  2. divide array into equal parts python
  3. divide array into equal parts javascript
  4. divide array into equal parts java
  5. divide array into 3 equal parts
  6. divide array into increasing sequences
  7. divide array into n equal parts
  8. divide array into k equal parts
  9. divide array into equal parts matlab
  10. divide array into k parts
  11. divide array into equal parts leetcode
  12. divide array into equal parts c++
  13. divide array into increasing sequence leetcode
  14. divide array into equal parts ruby
  15. divide array into segments
  16. divide array into 4 equal parts
  17. divide array into equal parts php
  18. divide array into two parts javascript
  19. divide array into subarrays java
  20. divide array into chunks

I'm working on a network visualization using Three.js and am having trouble determining why my ray casting implementation is not identifying the correct points (Full example and source). More ...

I'm working on a network visualization using Three.js and am having trouble determining why my ray casting implementation is not identifying the correct points (Full example and source). More ...