如何遍历 HTML 元素并填充 Json 对象?

How to loop through HTML elements and populate a Json-object?

我正在循环遍历 html 文件中的所有 html 标签,检查这些标签是否符合条件,并尝试组成一个 JSON-object of a following架构:

[
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  },
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  },
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  }
]

但我只想为分类为 "header" 的元素创建新条目,所有其他元素都必须添加到之前创建的条目中。我该如何实现?

当前代码:

$('*').each((index, element) => {


  if ( $(element).hasClass( "header" ) ) {
      jsonObject.push({
          title: $(element).text()
      });
  };
  if( $(element).hasClass( "date" )) {
      jsonObject.push({
          date: $(element).text()
      });
   }

   //links.push($(element))
});
console.log(jsonObject)

结果是:

  {
    title: 'TestA'
  },
  { date: '10.10.10' },
  {
    title: 'TestB'
  },
  { date: '10.10.11' }

我希望它在这个阶段是这样的:

      {
        title: 'TestA'
      ,
       date: '10.10.10' },
      {
        title: 'TestB'
      ,
       date: '10.10.11' }

更新: 这是 HTML 文件的示例:

<h1 class="header">H1_Header</h1>
<h2 class="date">Date</h2>
<p>A.</p>
<p>B.</p>
<p>С.</p>
<p>D.</p>
<a class="source"><a href="http://">http://</a></a>
<h1 class="header">H1_Header2</h1>
<h2 class="date">Date2</h2>
<p>A2.</p>
<p>B2.</p>
<p>С2.</p>
<p>D2.</p>
<a class="source"><a href="http://2">http://2</a></a>

感谢您的宝贵时间!

$('*').each((index, element) => {
  var obj = {};

  if ( $(element).hasClass( "header" ) ) {
    obj.title = $(element).text();
  };
  if( $(element).hasClass( "date" )) {
    obj.date = $(element).text()
   }

    jsonObject.push(obj);

});

我不知道 jQuery,但是 JavaScript 你可以做这样的事情。

const arr = [];
document.querySelectorAll("li").forEach((elem) => {
  const obj = {};
  const title = elem.querySelector("h2");
  const date = elem.querySelector("date");
  if (title) obj["title"] = title.textContent;
  if (date) obj["date"] = date.textContent;
  arr.push(obj);
});
console.log(arr);
<ul>
  <li>
    <h2>A</h2>
    <date>1</date>
  </li>
  <li>
    <h2>B</h2>
  </li>
  <li>
    <date>3</date>
  </li>
</ul>

根据您的示例 Html,您尝试收集的所有内容似乎都按线性顺序排列,因此您会得到标题、日期、body 和 link,然后是新的 header 与您想要收集的相关物品,因为这似乎没有在 non-linear fasion 中订购物品的复杂性,您可以执行以下操作:

let jsonObject = null;
let newObject = false;
let appendParagraph = false;
let jObjects = [];

$('*').each((index, element) => {
  if ($(element).hasClass("header")) {
      //If newObject is true, push object into array
      if(newObject)
         jObjects.push(jsonObject);
      //Reset the json object variable to an empty object
      jsonObject = {};
      //Reset the paragraph append boolean
      appendParagraph  = false;
      //Set the header property
      jsonObject.header = $(element).text();
      //Set the boolean so on the next encounter of header tag the jsobObject is pushed into the array
      newObject = true;
  };

  if( $(element).hasClass( "date" )) {
      jsonObject.date = $(element).text();
  }

  if( $(element).prop("tagName") === "P") {
      //If you are storing paragraph as one string value
      //Otherwise switch the body var to an array and push instead of append
      if(!appendParagraph){ //Use boolean to know if this is the first p element of object
         jsonObject.body = $(element).text();
         appendParagraph = true; //Set boolean to true to append on next p and subsequent p elements
      } else {
         jsonObject.body += (", " + $(element).text()); //append to the body
      }

  }

  //Add the href property
  if( $(element).hasClass("source")) {
       //edit to do what you wanted here, based on your comment:
       jsonObject.link = $(element).next().html(); 
       //jsonObject.href= $(element).attr('href');
  }
});

//Push final object into array
jObjects.push(jsonObject);

console.log(jObjects);

这里有一个 jsfiddle:https://jsfiddle.net/Lyojx85e/

我无法获取 fiddle 上锚标签的文本(我相信是因为嵌套的锚标签无效,浏览器会将其解析为单独的锚标签),但提供的代码应该在现实世界的例子中工作。如果 .text() 不起作用,您可以将其切换到 link 上的 .html(),我对您在这个问题上想要得到的东西感到困惑,所以我更新了答案以获得link 的 href 属性,看起来就是您想要的。问题是带有 class 的锚没有 href 属性,所以我会留给你自己修复那部分,但这个答案应该给你你需要的。

像这样的事情总是使用地图。这应该看起来像:

let objects = $('.header').get().map(el => {
  return {
    date: $(el).attr('date'),
    title: $(el).attr('title'),
  }
})