Как извлечь данные из xml файла, JS
Столкнулся с проблемой, подключаюсь к xml файлу, в нём есть теги offers>offer.
Получаю массив тегов, где содержится вся информация: заголовок, описание, размер, цена и т.д. Но проблема в том, что размеры есть у основного товара и у цвета товара, и эти данные нвходятся в разных офферах. Мне нужно их как-то отфильтровать.
В коде, представленном ниже, я фильтрую по vendorCode, но у цвета и у основной карточки разные vendorCode.
Хочу создать новый массив c объектами, но там не за что зацепиться, чтобы собрать данные как единый товар. Какие еcть мысли по этому поводу?
Сайт с примером: https://kwork.aswebgroups.ru
Мой код:
const url = 'https://kwork.aswebgroups.ru/proxy.php?url=https://fireboxstore.ru/link/789ed662efe90852e79444d36545af7deda4d94a.xml';
const parser = new DOMParser();
const mycart = document.getElementById('mycart');
const mycartbt = document.getElementById('mycartbt');
let count = 3;
let card = '';
const uniqueIds = new Set();
const el = [];
let missingSizeOffers=[];
mycartbt.addEventListener('click', displayProductCards);
async function loadOffers() {
try {
const response = await fetch(url);
const xmlData = await response.text();
const xmlDoc = parser.parseFromString(xmlData, 'text/xml');
const offers = xmlDoc.querySelectorAll('shop > offers > offer');
console.log( offers[7])
offers.forEach(function (e) {
const id = e.getAttribute('id');
const url = e.querySelector('url').textContent;
const vendorCode = e.querySelector('vendorCode').textContent;
let nameParam = e.querySelector('param[name="Размер"]') != null?e.querySelector('param[name="Размер"]').textContent:"";
//8missingSizeOffers.push(nameParam);
const pictures = [...e.querySelectorAll('picture')];
var picture= pictures.map(function (el) {
return el.textContent
});
if (uniqueIds.has(id) || el.some(item => item.vendorCode === vendorCode)) {
// missingSizeOffers=[]
return; // Пропустить дубликаты
}
//console.log(missingSizeOffers)
const name = e.querySelector('name').textContent;
const description = e.querySelector('description').textContent;
el.push({
name,
url,
description,
picture,
id,
vendorCode,
});
});
} catch (error) {
console.error('Ошибка загрузки данных:', error);
}
}
function displayProductCards() {
card = '';
for (let i = 0; i < count; i++) {
if (i >= el.length) {
// Все товары добавлены
break;
}
const id = el[i].id;
if (uniqueIds.has(id)) {
continue; // Пропустить дубликат
}
uniqueIds.add(id);
card += `
<div class="cart">
<h3 class="product-name">${el[i].name}</h3>
<div class="img_carts"><img src="${el[i].picture[1]}" alt="${el[i].name}"></div>
<p class="product-description">${el[i].description}</p>
<a href="${el[i].url}" target="_blank">Подробнее</a>
</div>
`;
}
mycart.insertAdjacentHTML('beforeend', card);
count += 3;
}
async function loadProductCards() {
await loadOffers();
displayProductCards();
}
loadProductCards();
html,body {
font-family: 'Roboto', sans-serif;
line-height:1.3;
}
body {
display: flex;
flex-direction:column;
height: 100%;
}
*{
box-sizing:border-box;
}
/* Стили для карточек товара */
.product-card {
border: 1px solid #ddd;
padding: 10px;
margin: 10px;
width: 200px;
display: inline-block;
}
.product-name {
font-weight: bold;
font-size: 18px;
}
.product-description {
margin-top: 10px;
}
.container {
max-width: 1200px ;
margin: 100px auto;
height: 100%;
}
/* Стили для кнопки "Добавить в корзину" */
.row {
padding: 0 20px;
display: flex;
gap:18px;
flex-flow: wrap row;
}
.cart a {
display: block;
margin-top: 10px;
}
.cart {
width: calc(100%/4) ;
flex: 1 0 calc(100%/4) ;
}
.img_carts img {
max-width: 100%;
width: 100%;
object-fit: contain;
height: auto;
}
.img_carts {
width: 100%;
margin: 10px 0;
}
#mycartbt {
display:block;
background-color: #0074d9;
color: #fff;
border: none;
padding: 10px 20px;
width: 124px;
cursor: pointer;
margin: 20px auto;
}
<div class="container">
<div class="row" id="mycart">
<!-- Здесь будут отображаться карточки товара -->
</div>
<button id="mycartbt">показать ещё </button>
</div>