Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

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."}},{...}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Does this work for you?

You can filter out empty key2 if you need

const vals = [...document.querySelectorAll(".someclass p")].reduce((acc, elem) => {
  const first = elem.firstChild;
  if (first.tagName === "STRONG" && first.textContent.match(/^d+./)) {
    acc.push({
      "key1": elem.textContent,
      "customtext": {
        "key2": [""]
      }
    })
  } else acc[acc.length - 1].customtext.key2[0] += elem.textContent;
  return acc
}, [])

console.log(vals)
<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...