我返回了以下JSON对象,我想访问所有“title”值。我已经能够获得所有“页面”的新对象,但不能获得“标题”。除了正确的事情,我已经尝试了一切!这里的“类似”问题是直接的阵列访问问题。这似乎涉及嵌套数组。请帮忙!感谢。
{
"batchcomplete": "",
"continue": {
"gsroffset": 15,
"continue": "gsroffset||"
},
"query": {
"pages": {
"22989": {
"pageid": 22989,
"ns": 0,
"title": "Paris",
"index": 1
},
"59134": {
"pageid": 59134,
"ns": 0,
"title": "Paris Commune",
"index": 13
},
"61371": {
"pageid": 61371,
"ns": 0,
"title": "Paris (disambiguation)",
"index": 2
},
"64129": {
"pageid": 64129,
"ns": 0,
"title": "Catacombs of Paris",
"index": 11
},
"76286": {
"pageid": 76286,
"ns": 0,
"title": "Disneyland Paris",
"index": 15
},
"89106": {
"pageid": 89106,
"ns": 0,
"title": "Paris–Brest–Paris",
"index": 8
},
"357488": {
"pageid": 357488,
"ns": 0,
"title": "Paris Saint-Germain F.C.",
"index": 10
},
"868936": {
"pageid": 868936,
"ns": 0,
"title": "Paris Gun",
"index": 14
},
"2397134": {
"pageid": 2397134,
"ns": 0,
"title": "Paris (Paris Hilton album)",
"index": 6
},
"7618874": {
"pageid": 7618874,
"ns": 0,
"title": "Paris syndrome",
"index": 9
},
"11217925": {
"pageid": 11217925,
"ns": 0,
"title": "Paris Hilton",
"index": 7
},
"23528038": {
"pageid": 23528038,
"ns": 0,
"title": "Paris Jackson (actress)",
"index": 5
},
"30242372": {
"pageid": 30242372,
"ns": 0,
"title": "Paris Agreement",
"index": 4
},
"45259235": {
"pageid": 45259235,
"ns": 0,
"title": "Paris Laxmi",
"index": 12
},
"55340805": {
"pageid": 55340805,
"ns": 0,
"title": "Paris Paris",
"index": 3
}
}
}
}
它希望我添加更多细节,但我不知道还能添加什么。
答案 0 :(得分:2)
试试这个:
const data = //your json
const pages = data.query.pages
const titles = Object.keys(pages).map( key => pages[key].title )
存储'页面中的值'在变量中,然后使用Object.keys将“'页面”中的所有键作为数组。然后使用map运算符迭代这些键,并为每个键返回属性' title'这个条目。
答案 1 :(得分:0)
如果你想使用lodash / underscore,这样的东西会起作用:
const dataPages = data["query"]["pages"];
let titles = [];
_.each(dataPages, (dataPage) => titles.push(dataPage["title"]))
这应该会给你一个标题数组!
答案 2 :(得分:0)
这使用Object.keys来枚举JSON中的页面。
"use strict"
const DATA = //your Map
const pages = DATA.query.pages;
const keys = Object.keys(pages); // returns an array of the ID numbers that are properties in each page
let titles = [keys.length]; // initialize an output array
for(let i=0; i < keys.length; i++){
titles[i] = pages[keys[i]].title;
};