【问题标题】:Trying to populate a nested json file to html [closed]尝试将嵌套的 json 文件填充到 html [关闭]
【发布时间】:2020-12-24 03:29:00
【问题描述】:

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

{
  "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"
  }
}

【问题讨论】:

标签: html json


【解决方案1】:

你可以使用reduce

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>

【讨论】:

  • 非常感谢你太棒了
  • 您好,先生,我还有一个问题,
  • 所以当我的json有链接时,
  • 我不希望整个链接显示在我的 html 上,而是我想将其转换为 HYPERLINK,
  • 查看更新代码
猜你喜欢
  • 2016-04-09
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 2016-06-28
  • 1970-01-01
  • 2014-06-20
相关资源
最近更新 更多