Вывести данные в 4 блока из массива объектов на нативном JS
Столкнулся с такой проблемой. У меня есть массив из 4 объектов, нужно их вывести в html.
<div class="sphere sphere--1">
<span class="sphere__text"></span>
<img class="sphere__img" src="" alt="">
</div>
<div class="sphere sphere--2">
<span class="sphere__text"></span>
<img class="sphere__img" src="" alt="">
</div>
<div class="sphere sphere--3">
<span class="sphere__text"></span>
<img class="sphere__img" src="" alt="">
</div>
<div class="sphere sphere--4">
<span class="sphere__text"></span>
<img class="sphere__img" src="" alt="">
</div>
function printLastSlideContent(gamePage, index) {
const slideSections = [...gamePage.querySelectorAll('#innerGameSwiper .section')];
const sphere = [...slideSections[index].querySelectorAll('.sphere')];
sphere.map(item => {
const name = item.querySelector('.sphere__text');
const img = item.querySelector('.sphere__img');
finalCategories.map(data => {
item.setAttribute('id', data.id);
name.textContent = data.name;
img.setAttribute('src', data.img);
})
});
}
Пояснение: finalCategories это массив из 4 объектов, содержимое которого нужно добавить в span и img.
Функция отрабатывает коряво, добавляются данные только из одного объекта во все 4 html.
Ответы (1 шт):
Автор решения: Lukas
→ Ссылка
const finalCategories = [{id:1,"img":"https://www.logaster.com/blog/wp-content/uploads/2020/03/0127.png"},{id:2,"img":"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/NASA_logo.svg/200px-NASA_logo.svg.png"},{id:3,"img":"https://static.rfstat.com/renderforest/images/v2/logo-homepage/flat_3.png"},{id:4,"img":"https://delo.ua/files/news/images/3644/62/picture2_v-google-maps-poj_364462_p0.png"}]
function printLastSlideContent() {
// const slideSections = [...gamePage.querySelectorAll('#innerGameSwiper .section')];
const sphere = [...document.querySelectorAll('.sphere')];
sphere.map((item, index) => {
const name = item.querySelector('.sphere__text');
const img = item.querySelector('.sphere__img');
let data = finalCategories[index];
name.setAttribute('id', data.id);
img.setAttribute('src', data.img);
});
}
printLastSlideContent();
.sphere img {
heigth:200xp;
width:200px;
}
<div class="sphere sphere--1">
<span class="sphere__text"></span>
<img class="sphere__img" src="" alt="">
</div>
<div class="sphere sphere--2">
<span class="sphere__text"></span>
<img class="sphere__img" src="" alt="">
</div>
<div class="sphere sphere--3">
<span class="sphere__text"></span>
<img class="sphere__img" src="" alt="">
</div>
<div class="sphere sphere--4">
<span class="sphere__text"></span>
<img class="sphere__img" src="" alt="">
</div>