首页 > 解决方案 > 尝试将嵌套的 json 文件填充到 html

问题描述

我希望它看起来像这样,如何在使用减速器时检测链接?在遍历 for 循环时,我想检测最后一列的链接并推送标签

2

{
  "alpha": {
    "phone": "11223344",
    "city": "nyc",
    "state": "ny",
    "link": "https://www.google.com/search?q=nyc+pictures&oq=nyc+pictures&aqs=chrome..69i57.3022j0j7&sourceid=chrome&ie=UTF-8"

  },
  "beta": {
    "phone": "11223344",
    "city": "nyc",
    "state": "ny",
    "link":"https://www.google.com/search?q=nyc+pictures&oq=nyc+pictures&aqs=chrome..69i57.3022j0j7&sourceid=chrome&ie=UTF-8"
  },
  "gamma": {
    "phone": "11223344",
    "city": "nyc",
    "state": "ny",
    "link": "https://www.google.com/search?q=nyc+pictures&oq=nyc+pictures&aqs=chrome..69i57.3022j0j7&sourceid=chrome&ie=UTF-8"
  }
}

标签: htmljson

解决方案


您可以使用减少

const data = { "alpha": { "phone": "11223344", "city": "nyc", "state": "ny", "link": "https://www.google.com/search?q=nyc+pictures&oq=nyc+pictures&aqs=chrome..69i57.3022j0j7&sourceid=chrome&ie=UTF-8" }, "beta": { "phone": "11223344", "city": "nyc", "state": "ny", "link":"https://www.google.com/search?q=nyc+pictures&oq=nyc+pictures&aqs=chrome..69i57.3022j0j7&sourceid=chrome&ie=UTF-8" }, "gamma": { "phone": "11223344", "city": "nyc", "state": "ny", "link": "https://www.google.com/search?q=nyc+pictures&oq=nyc+pictures&aqs=chrome..69i57.3022j0j7&sourceid=chrome&ie=UTF-8" } }

document.getElementById("tb").innerHTML = Object.entries(data)
  .reduce((acc, ent) => {
    acc.push(`<tr><td>${ent[0]}</td>`);
    Object.entries(ent[1])
      .forEach(([key,val]) => acc.push(
        key === 'link' ? `<td><a href="${val}">Go</a></td>` : `<td>${val}</td>`
      ));
    acc.push(`</tr>`);
    return acc;
  }, []).join('');
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Phone</th>
      <th>City</th>
      <th>State</th>
      <th>Link</th>
  </thead>
  <tbody id="tb">
  </tbody>
</table>


推荐阅读