Помогите сделать массив объектов из коллекций
Есть HTML разметка вида
<article>
<h3>Title</h3>
<div><strong>Author1</strong>
<p>desc1</p>
</div>
<div><strong>Author2</strong>
<p>desc2</p>
<p>desc2</p>
</div>
<div><strong>Author3</strong>
<p>desc3</p>
<p>desc3</p>
<p>desc3</p>
</div>
</article>
Соответственно из этого нужно сделать массив объектов такого вида
const arr = [{title: "Title", author: "Author1", desc: ["desc1"]}, {title: "Title", author: "Author2", desc: ["desc2", "desc2"]}, {title: "Title", author: "Author3", desc: ["desc3", "desc3", "desc3"]}]
Я еще совсем новичок в js, перепробовал кучу вариантов но все никак не выходит. Буду очень благодарен за помощь.
Ответы (1 шт):
Автор решения: Pilaton
→ Ссылка
Так думаю понятно будет как можно было сделать.
const arr = [];
let divs = document.querySelectorAll('div');
for (const div of divs) {
let tempObj = {};
tempObj.title = document.querySelector('h3').textContent;
tempObj.author = div.querySelector('strong').textContent;
tempObj.desc = Array.from(div.querySelectorAll('p')).map((p) => p.textContent);
arr.push(tempObj);
}
console.log('arr', arr);
<article>
<h3>Title</h3>
<div><strong>Author1</strong>
<p>desc1</p>
</div>
<div><strong>Author2</strong>
<p>desc2</p>
<p>desc2</p>
</div>
<div><strong>Author3</strong>
<p>desc3</p>
<p>desc3</p>
<p>desc3</p>
</div>
</article>