代码
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);
我试图访问字符串&#34; 15&#34;和&#34; 390&#34;,但循环遍历它们只是给我每个组的整个对象。我如何只提取数字字符串,以便我可以用它们构建数组?
答案 0 :(得分:5)
您可以在对象上使用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>