김진창
김진창

Reputation: 105

how can i access nested json data in angular2

this is my app.component.ts

@Component({
  selector: 'my-app',
  template: `<h1>{{title}}</h1>
  {{test | json}}

  <div ngFor='let test of tests' style='border: solid 1px'>
    <div>
      <P>
        writer: {{test.A.B.C.D.writerid}} <br>
        content:{{test}}<br>
        write_date:{{test}}</P>
    </div>
  </div>
  `,
})

public test: any[] = [
 {
   'A': {
     'B': [{
       'C': {
         'D': [{
           'content': 'content_test1',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test1'
          }, {
           'content': 'content_test2',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test1'
          }, {
            'content': 'content_test3',
            'writedt': '2017-02-08 00:00:00',
            'writerid': 'writerid_test2'
         },  {
           'content': 'content_test4',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test2'
         }]
       }
     }]
   }
 }
];

test.A.B.C.D.writerid is not working error:Cannot read property 'B' of undefined i don't understand why error is not A but B how can i access D's content or writedt or writerid

Upvotes: 4

Views: 7416

Answers (2)

Yuvraj Patil
Yuvraj Patil

Reputation: 8726

You should access it as below:

test[0].A.B[0].C.D[0].writerid

Upvotes: 0

AVJT82
AVJT82

Reputation: 73357

First of all, I assume you have some typos in your template (e.g ngFor), and that the array is actually called tests but let's disregard that.

I guess you want to iterate through the array of D. Without making any changes to your structure of your data, you can do it with nested *ngFor:s.

So first your array should be named tests, not test. And how to access the most inner array, we'll first iterate the tests array, after that iterate through array B and lastly the innermost array D. So your template would look like this:

  <div *ngFor="let test of tests">
    <div *ngFor="let x of test.A.B">
      <div *ngFor="let y of x.C.D; let i = index"> <h4>Content {{i+1}}</h4>
        {{y.content}}
        {{y.writedt | date}}
        {{y.writerid}}
      </div>
    </div>
  </div>

DEMO

Upvotes: 3

Related Questions