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

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

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

Post 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>
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply