0

I have a response for Angular 11 TypeScript code like:

{
  "Id": "12345",
  "length": [
    {
      "a": {
        "1": {
          "test": [
            {
              "days": "20"
            }
          ]
        }
      }
    }
  ]
}

It is unable to fetch data as one parameter is "1". It’s giving a compilation issue when trying to print the value of days like:

console.log(length[0].a.1.test[0].days);

If it’s "one" instead of "1" it’s working fine:

console.log(length[0].a.one.test[0].days);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • try using `a['1'].test....` – depperm May 07 '21 at 11:04
  • console.log(length[0].a['1'].test[0].days)...if i write like this test is coming as undefined and also a is not an array..its a param inside length array – pranav verma May 07 '21 at 11:09
  • its a difference between dot and bracket notation. Brackets can be used for objects not just arrays. See also [this answer](https://stackoverflow.com/a/4968448/3462319) – depperm May 07 '21 at 11:13
  • ya @depperm but i am not getting the data even after using a['1'].test[0].days..its gave test as undefined in chrome console – pranav verma May 07 '21 at 11:16
  • What are the exact error messages? You may consider adding this and other information by [editing (changing) your question](https://stackoverflow.com/posts/67433740/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the question should appear as if it was written today). Thanks in advance. – Peter Mortensen Mar 13 '22 at 12:59

2 Answers2

1

You need to pass the key in square brackets to get the data.

Example

a = {
    Id: '12345',
    length: [
      {
        a: {
          '1': {
            test: [
              {
                days: '20'
              }
            ]
          }
        }
      }
    ]
};

console.log(this.a.length[0]['a']['1'].test[0].days); // output ==> 20

You can also play with the code here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kiran Mistry
  • 2,614
  • 3
  • 12
  • 28
1

Try this working solution. It should work now.

const data = {
  "Id": "12345",
  "length": [
    {
      "a": {
        "1": {
          "test": [
            {
              "days": "20"
            }
          ]
        }
      }
    }
  ]
}


console.log(data.length[0].a[1].test[0].days) // returns "20"
Yuva Raj
  • 3,881
  • 1
  • 19
  • 30
  • i am trying to get the details in html..i have a for loop for length array like *ngFor="let item of length" and i am trying to fetch data by item.a[1].test and applying one more loop to fetch days based on index of test...but in html a[1] did not worked like that of ts..how to do can u guide please – pranav verma May 07 '21 at 13:25