簡體   English   中英

如何使用入門鍵從JSON對象中構建數組?

[英]How do I build an array out of a JSON object with starter keys?

var q = JSON.parse('[{"15": {"bUrl": "https://example.com/r2359","name": "Ninpo","url": null,"desc": null,"series": [{"title": "Nana","id": "6308","authors": ["Author1"]}]}}, {"390": {"bUrl": "https://example.com/r2667","name": "Sanpo","url": null,"desc": null,"series": [{"title": "Baba","id": "6498","authors": ["Author2"]}]}}]');

var yy = [];
for (i = 0; i < q.length; i++) {
    yy.push(q[i]);
}
console.log(yy);

我正在嘗試訪問字符串“ 15”和“ 390”,但是循環訪問它們只是為我提供了每個組的整個對象。 如何僅提取數字字符串,以便可以使用它們構建數組?

您可以在對象上使用Object.keys來獲取密鑰作為數組,並結合使用Array#reduceArray#concat將密鑰平面映射到單個數組中。

 var q = JSON.parse('[{"15": {"bUrl": "https://example.com/r2359","name": "Ninpo","url": null,"desc": null,"series": [{"title": "Nana","id": "6308","authors": ["Author1"]}]}}, {"390": {"bUrl": "https://example.com/r2667","name": "Sanpo","url": null,"desc": null,"series": [{"title": "Baba","id": "6498","authors": ["Author2"]}]}}]'); console.log( Object.keys(q[0]) ) console.log( q.reduce((acc, x) => acc.concat(Object.keys(x)), []) ) 
 <script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script> 

暫無
暫無

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

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