簡體   English   中英

如何使用 javascript 解碼 json 循環數據

[英]How to decode json loop data using javascript

我在 package 跟蹤 API 工作,它返回 json 中的數據

我正在使用 javascript 到 output 的數據

前三個輸出是完美的,但問題是“current_status”和“statuses”有縮進/嵌套數據,如何 output 呢?

 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>

你可以 map

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM