jeudi 7 janvier 2021

How to loop in javascript until condition is met and add the results to an array?

I need to push two key/value pairs to an array based on the different conditions.

Condition for the first key/value: only paragraph starting with the number.

Condition for the second key/value: all paragraphs after the first key/value pair (until the next paragraph starting with number).

Here is the html example:

<div class="someclass">
    <p><strong>1. Some text</strong></p>
    <p>Some text related to 1.</p>
    <p>Some other <a href="/someurl"><strong> text</strong></a> related to 1.</p>
    <p><strong>2. Some other text</strong></p>
    <p>Some text related to 2.</p>
    <p><strong>3. Can you send me a catalog?</strong></p>
    ...
</div>

I am able to get only one paragraph for the second key/value pair with this javascript code:

var array = [];
var allParagraphs = document.querySelectorAll("someclass p");
for (i = 0; i < allParagraphs.length; i++) {
    if (/^\d/.test(allParagraphs[i].innerText) === true) {
        array.push({
            "key1": allParagraphs[i].innerText,
            "customText": {
                "key2": allParagraphs[i + 1].innerText
            }
        });
    }
}

The output I get is something like:

[{key1: "1. Some text", customText: {key2: "Some text related to 1."}},{key1: "2. Some text", customText: {key2: "Some text related to 2."}},{...}]

And I need to get something like this:

[{key1: "1. Some text", customText: {key2: "Some text related to 1. Some other text related to 1."}},{key1: "2. Some text", customText: {key2: "Some text related to 2."}},{...}]

Aucun commentaire:

Enregistrer un commentaire