Home > Software design >  :: jQuery :: JSON Find first key and replace dynamically
:: jQuery :: JSON Find first key and replace dynamically

Time:10-07

I am trying to get json data and displaying table format. However it is working as expected if I use first key/object (heading) as manual.

Sample JSON files for the same:

  • enter image description here

    enter image description here

    Code:

    var atd, atr, temp;
    
    fetch('https://amp.gmail.dev/playground/public/ssr_amp_list')
        .then((response) => response.json())
        .then((data) => {
        data.items.map(myList => {
            var __keys = Object.keys(myList); 
            var __values = Object.values(myList);
            $.each(__values, function(index,myList) {
                atd = '<td>' myList '</td>'
                atr  = atd;
                if((__keys.length) -1 == index){
                    temp =  '<tr>' atr '</tr>'
                    atr = '';
                }
            })
        });
        $('#data table').html(temp) 
    })
    

    Output: enter image description here

    Another JSON file: enter image description here

    For the above JSON file, I have to change code as:

    data.site.docs.map(myList => {
    

    enter image description here

    CodePudding user response:

    Please try this solution

    Get all the nested child arrays and use the arrays to display data. Here I have only used the first array. You can iterate and use all arrays if needed.

    http://jsfiddle.net/r0uocnzv/

    var atd, atr, temp;
    let resultData = [];
    //fetch('https://api.plos.org/search?q=title:DNA')
    fetch('https://amp.gmail.dev/playground/public/ssr_amp_list')
        .then((response) => response.json())
        .then((data) => {
      findChildArrays(data);
      console.log(resultData)
       if(resultData && resultData[0]) {
        resultData[0].map(myList => {
          var __keys = Object.keys(myList); 
          var __values = Object.values(myList);
          $.each(__values, function(index,myList) {
            atd = '<td>' myList '</td>'
            atr  = atd;
            if((__keys.length) -1 == index){
              temp =  '<tr>' atr '</tr>'
              atr = '';
            }
          })
        });
      } 
    
        $('#data table').html(temp) 
    });
    
    findChildArrays = function(data = {}) {
      Object.keys(data).forEach(key => {
        if(Array.isArray(data[key])) {
             resultData.push(data[key])
        }
      else
        findChildArrays(data[key] || [], )
      });
      return resultData;
    };
    
  • Related