Page 1 of 1

//I have a nested array that looks like this (It's a huge dataset and this is just an example of the array format): ' [

Posted: Thu May 05, 2022 1:40 pm
by answerhappygod
//I have a nested array that looks like this (It's a huge
dataset and this is just an example of the array format): '
[
{
"id": "e153e96a423fa88b8d5ff2d473de0481e49",
"gender": "male",
"name": "Tom",
"url" : ...,
"legal": [
{
"type": "attribution",
"text": "A student of Geography",
}
]
},
{
"id": "89fjudjw88b8d5ff2d473de0481e49",
"gender": "male",
url: ...
"name": "Nate",
"legal": [
{
"type": "attribution",
"text": "A student of Maths",
}
]
}
]
//using foreach to loop through and retrieve the data, but it
isn't looping through the ```legal[]``` nested array. Here's my
code. What am I missing?
const createElement = (tag, ...content) => {
const el = document.createElement(tag);
el.append(...content);
return el;
};
const renderData = (entity) =>{
console.log(JSON.stringify(entity))
let entityProps = Object.keys(entity)
console.log(entityProps)
const dl = document.createElement('dl');
entityProps.forEach (prop => {
prop.childrenProp.forEach(propNode => {
const pre_id = document.createElement('pre');
const dt_id = document.createElement('dt');
dt_id.textContent = prop;
pre_id.appendChild(dt_id);
const dd_id = document.createElement('dd');
if (prop == "url") {
const link = document.createElement('a');
link.textContent = entity[prop];
link.setAttribute('href', '#')
link.addEventListener('click',function(e) {
console.log("A working one!")
console.log(e.target.innerHTML)
fetchData(e.target.innerHTML)
});
dd_id.appendChild(link);
} else {
dd_id.textContent = entity[prop];
}
pre_id.appendChild(dd_id);
dl.appendChild(pre_id);
});
return dl;
}}
const results = document.getElementById("results");
// empty the <div>
results.innerHTML = '';
//function call
function fetchData(url){
fetch(url
)
.then((res) => (res.ok ? res.json() :
Promise.reject(res)))
.then((data) => {
results.append(
...data.flatMap((entry) => [
renderData((entry)),
document.createElement("br"),
document.createElement("br"),
])
);
})
.catch(console.error);
}
const data=document.getElementById("data");
catalog.addEventListener("onclick",
fetchData(`http://data:8003/v1/entry/`));
//html
<body>
<button id="data">View Catalog</button>
<div id="results"></div>