I have an API I'm trying to fetch and display data from. The data I want to access is in the 'equipments' array as shown below.
I'm trying to loop through the 'equipments' array for each item but I'm having trouble displaying the data. I believe I'm either not accessing it properly, or not including another loop somewhere.
Here's what I have so far:
// Fetch Data
function getData() {
fetch(url)
.then((res) => res.json())
.then((data) => {
let output = "";
data.groups.equipments.forEach(function(product) {
output += `
<div class="card">
<img src=${product.photos.text} alt=${product.model} />
<h3>${product.year} ${product.manufacturer} ${product.model}</h3>
<p>${product.hours} hours</p>
<a href='https://used.battlefieldequipment.ca/en/${product["group-code"]}/${product.equipments["serial-number"]}' class="btn btn-primary">View Details</a>
</div>
`;
});
dataOutput.innerHTML = output;
})
}
getData();
Any idea what I need to do in order to get this working?
5 Answers 5
Since data.groups is an array, you first have to iterate through them before accessing the equipments.
You can also iterate through them using a forEach, so that's easy!
data.groups.forEach(function(group) {
group.equipments.forEach(product) {
output += `
<div class="card">
<img src=${product.photos.text} alt=${product.model} />
<h3>${product.year} ${product.manufacturer} ${product.model}</h3>
<p>${product.hours} hours</p>
<a href='https://used.battlefieldequipment.ca/en/${product["group-code"]}/${product.equipments["serial-number"]}' class="btn btn-primary">View Details</a>
</div>`;
}
})
Comments
instead of groups.equipments use
groups.map((g) => g.equipments)
Comments
You are trying to get the equipments property of the array. The property is in the object which is inside the array.
data.groups.forEach(obj => {
//obj.equipments is what you want now. It returns the equipments property of current object in the loop
})
Comments
You have to make twice forEach. Check here https://js.do/code/621480
Data groups is array also, so you have to take foreach group then foreach product in equipments.
Comments
const loadApi = async () => {
let url = await fetch(url)
let res = await url.json();
for (const element of res.groups) {
for (const element2 of element.equipments) {
getItemsFromProducts(element2);
}
}
}; loadApi();
const getItemsFromProducts = (data) => {
let demo = document.getElementById('demo');
demo.innerHTML = `
<div id="product">
<img src=${data.photos[0].text} alt=${data.model} />
<h3>${data.year} ${data.manufacturer} ${data.model}</h3>
<p>${data.hours} hours</p>
</div>
`;
}
1 Comment
Explore related questions
See similar questions with these tags.
data.groupsis an array, too!