如何使用JavaScript解码JSON循环数据

汉娜·詹姆斯(Hannah James)

我正在使用包裹跟踪API,并且它以json返回数据

我正在使用javascript输出数据

前三个输出是完美的,但问题是“ current_status”和“ statuses”具有缩进/嵌套数据,如何输出它们?

const data = {
  "packet_id": "0024-00003711",
  "consignee_name": "Nasir maqbool",
  "destination": "Lahore",
  "current_status": {
    "status": "Assigned to Courier",
    "datetime": "2020-12-27T17:55:05.414Z",
    "comment": null
  },
  "statuses": [{
    "status": "Pickup request sent",
    "datetime": "2020-12-27T09:55:41.295Z",
    "comment": null
  }, {
    "status": "Booked",
    "datetime": "2020-12-26T10:13:15.333Z",
    "comment": null
  }]
}

let html = "";

html += '<div><strong>Packet Id:</strong> ' + data.packet_id + '</div>';
html += '<div><strong>Consignee Name:</strong> ' + data.consignee_name + '</div>';
html += '<div><strong>Destination:</strong> ' + data.destination + '</div>';
html += '<div><strong>Current Status:</strong>???</div>';
html += '<div><strong>Status:</strong> ???</div>';
$("#response").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="response"></div>

mplungjan

你可以地图

const data = { "packet_id": "0024-00003711", "consignee_name": "Nasir maqbool", "destination": "Lahore", "current_status": { "status": "Assigned to Courier", "datetime": "2020-12-27T17:55:05.414Z", "comment": null }, "statuses": [{ "status": "Pickup request sent", "datetime": "2020-12-27T09:55:41.295Z", "comment": null }, { "status": "Booked", "datetime": "2020-12-26T10:13:15.333Z", "comment": null }] };


const curStatus = Object.entries(data.current_status)
  .map(entr => `<li>${entr[0]}:${entr[1]}</li>`) // map the entries 
  .join("") // join
  
const statuses = data.statuses
  .map(ent => Object.entries(ent) // map each status
    .map(entr => `<li>${entr[0]}:${entr[1]}</li>`) // map the entries in the statuses
      .join("") // join
  ).join("</ul><hr><ul>") // join with a separator
  
const html = `<div><strong>Packet Id:</strong>${data.packet_id}</div>
<div><strong>Consignee Name:</strong>${data.consignee_name}</div>
<div><strong>Destination:</strong>${data.destination}</div>
<div><strong>Current Status:</strong><ul>${curStatus}</ul></div>
<div><strong>Previous statuses:</strong><ul>${statuses}</ul></div>`
$("#response").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="response"></div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章