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:
-
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) })
For the above JSON file, I have to change code as:
data.site.docs.map(myList => {
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.
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; };