Using Cheerio, I need to iterate on multiple levels to access elements. how to use a nested iteration to access elements and return an array of objects? Currently with my code, because of the nested loop, I am returning an array of arrays of objects.
the html:
<code><body style="overflow: hidden">
<div class="cookie-box"></div>
<div id="next">
<div></div>
<div>
<main id="main">
<article>
<div>
<h2>title</h2>
</div>
<div></div>
<div class="layout">
<form></form>
<section aria-labelledby="Train">
<ul>
<li>
<p>title</p>
<span>
<a>
<span>123</span>
</a>
<a>
<span>456</span>
</a>
...
</span>
...
</li>
<li></li>
...
</ul>
</section>
</div>
</article>
</main>
</div>
</div>
</body>
</code>
<code><body style="overflow: hidden">
<div class="cookie-box"></div>
<div id="next">
<div></div>
<div>
<main id="main">
<article>
<div>
<h2>title</h2>
</div>
<div></div>
<div class="layout">
<form></form>
<section aria-labelledby="Train">
<ul>
<li>
<p>title</p>
<span>
<a>
<span>123</span>
</a>
<a>
<span>456</span>
</a>
...
</span>
...
</li>
<li></li>
...
</ul>
</section>
</div>
</article>
</main>
</div>
</div>
</body>
</code>
<body style="overflow: hidden">
<div class="cookie-box"></div>
<div id="next">
<div></div>
<div>
<main id="main">
<article>
<div>
<h2>title</h2>
</div>
<div></div>
<div class="layout">
<form></form>
<section aria-labelledby="Train">
<ul>
<li>
<p>title</p>
<span>
<a>
<span>123</span>
</a>
<a>
<span>456</span>
</a>
...
</span>
...
</li>
<li></li>
...
</ul>
</section>
</div>
</article>
</main>
</div>
</div>
</body>
the code:
<code>const data = [...$('[aria-labelledby="Train"] li')].map(e => {
return [...$item.find('span a')].map(elem=> {
return {
p: $(e).find("p").text(),
number: $(elem).find('span').text()
}
})
});
</code>
<code>const data = [...$('[aria-labelledby="Train"] li')].map(e => {
return [...$item.find('span a')].map(elem=> {
return {
p: $(e).find("p").text(),
number: $(elem).find('span').text()
}
})
});
</code>
const data = [...$('[aria-labelledby="Train"] li')].map(e => {
return [...$item.find('span a')].map(elem=> {
return {
p: $(e).find("p").text(),
number: $(elem).find('span').text()
}
})
});
what I would want as output:
<code>[
{
p: "title",
num: 123
},
{
p: "title",
num: 456
}
]
</code>
<code>[
{
p: "title",
num: 123
},
{
p: "title",
num: 456
}
]
</code>
[
{
p: "title",
num: 123
},
{
p: "title",
num: 456
}
]
what I get:
<code>[
[
{
p: "title",
num: 123
},
{
p: "title",
num: 456
}
]
]
</code>
<code>[
[
{
p: "title",
num: 123
},
{
p: "title",
num: 456
}
]
]
</code>
[
[
{
p: "title",
num: 123
},
{
p: "title",
num: 456
}
]
]
1