[英]How do I loop through a JSON object in MarkLogic to push all the keys in an array?
[英]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#reduce
和Array#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.