Iterate Json Data in JavaScript/TypeScript

后端 未结 2 1342
感情败类
感情败类 2021-01-19 15:00

I need to Iterate on this Json Data and add value to the Grid in JavaScript(TypeScript) No Jquery.

{\"GridHeader\":{\"Id\":\"Id\",\"Name\":\"Full Name\",\"Ag         


        
相关标签:
2条回答
  • 2021-01-19 15:27

    Your going to have to explain in more detail what you mean by "iterate on the data".

    {
       "GridHeader":{
          "Id":"Id",
          "Name":"Full Name",
          "Age":"Age"
       },
       "GridData":{
          "Id":3,
          "name":"Vu",
          "age":34
       }
    }
    

    Does not have any Arrays present in it.

    If it did have arrays in it, then I'm going to assume you meant something like this:

    "mydata":{
       "GridHeader":{
          "Id":"Id",
          "Name":"Full Name",
          "Age":"Age"
       },
       "GridData":[
            {
              "Id":3,
              "name":"Vu",
              "age":34
            },
            {
              "Id":2,
              "name":"Vu2",
              "age":33
            },
            {
              "Id":1,
              "name":"Vu1",
              "age":32
            }
       ] 
    }
    

    If your data looks like that, then you have an array of objects in your grid data, and you would then be able to use something like this:

    mydata.GridData.forEach(item){
      // DO something with
      // item.Id
      // item.Name
      // item.Age
    }
    

    Within the loop your code will get called once for each object in the GridData part of your parent and allow you access to each of the 3 properties for each individual item.

    However, looking at your data the way it is, then it's just a simple object.

    If we imagine you have it in a variable called myData, then you can access it's parts as follows:

    myData.GridHeader.Id
    myData.GridHeader.Name
    myData.GridHeader.Age
    

    To get the header properties.

    myData.GridData.Id
    myData.GridData.Name
    myData.GridData.Age
    

    To get at the properties of the one and only non iterable object you have present.

    0 讨论(0)
  • 2021-01-19 15:40

    Yes, your data is actually a javascript object below:

    var header = {
        "GridHeader":{"Id":"Id","Name":"Full Name","Age":"Age"},
      "GridData":   {"Id":3,"name":"Vu","age":34}
      };
    

    And you can loop through it like below:

    for (var prop in header) {
            console.log("Key:" + prop);
            console.log("Value:" + header[prop]);
        }
    

    Please, make it according to your needs. I have give you a clue to iterate it. Thanks.

    0 讨论(0)
提交回复
热议问题