0

I have my json like this. I need to get the data whose index is 101. Is there smarter way to query that.

[{
  "Name": "Ana",
  "Class": 3,
  "index": 0,
  "Subject": [
    {
      "Sub1": "Maths",
      "Sub2": "Science",
      "index": 00,
      "Speciality": [
        {
          "Spcl": "Music",
          "Spcl2": "Sports",
          "Spcl3": "Singing",
          "index": "000"
        }
      ]
    }
  ]
},
{
  "Name": "Ben",
  "Class": 3,
  "index": 1,
  "Subject": [
    {
      "Sub1": "Maths",
      "Sub2": "Science",
      "index": 10,
      "Speciality": [
        {
          "Spcl": "Music",
          "Spcl2": "Sports",
          "Spcl3": "Singing",
          index: 100
        },{
          "Spcl": "Music",
          "Spcl2": "Sports",
          "Spcl3": "Singing",
          "index": "101"
        }
      ]
    }
  ]
},
{
  "Name": "David",
  "Class": 3,
  "index": 2,
  "Subject": [
    {
      "Sub1": "Maths",
      "Sub2": "Science",
      "index": 20,
      "Speciality": [
        {
          "Spcl": "Music",
          "Spcl2": "Sports",
          "Spcl3": "Singing",
          "index": "200"
        }
      ]
    }
  ]
}]

Here is what I am trying.

accessData(myData,index) {
// my index in 101 for example

    for(var i=0; i<index.length; i++){
        if(index.length == 3){
            my result = myData[i].subject[i+1].Speciality[i+2]
        }if(index.length == 3){
            my result = myData[i].subject[i+1]
        }else{
                my result = myData[i];
        }
    }
    
    )
}

But here my subject and specity may changes in some time so I want to query at index level and do my operation. Is there any way to get that.

David
  • 4,266
  • 8
  • 34
  • 69
  • Recursively iterate over the data until you find the object with the right property. – Felix Kling Sep 04 '20 at 12:20
  • You can use a nested flat-map: https://jsfiddle.net/4sv2du3x/ – Nick Parsons Sep 04 '20 at 12:25
  • `index` seems to be a `Number` (not a `String`), cannot be `000` (is `0`). If you wand a `String`, put double-quotes (`"`), like so: `"000"`. Sometimes your `index` is with, and sometimes without, double-quotes. Also, please give an example of what you expect to get. Where you have `i+1` or `i+2`, do you mean `i*10` or `i+"0"` (and similar for `+2`)? – iAmOren Sep 04 '20 at 12:27
  • @iAmOren index i have updated. – David Sep 04 '20 at 12:32
  • @NickParsons Ya, My point can i get the result based on index becaus my data may get replace with `sunject` or `specilty` sometime. – David Sep 04 '20 at 12:33
  • @FelixKling is there any example for this. – David Sep 04 '20 at 12:56
  • See "What if the "depth" of the data structure is unknown to me?" in the duplicate. – Felix Kling Sep 04 '20 at 12:59
  • @FelixKling by iterating I may achive what I want. thats why I am looking for the query bases solution in plaine js. Even I am also focusing in that – David Sep 04 '20 at 13:01

0 Answers0