假设我有一个 JSON 数组,每个对象包含一堆不同的键/值。我知道如何使用 Javascript 来定位特定的键/值,但是如果我想搜索整个 JSON 文件以查找某个项目,然后在同一对象中查找相关对,该怎么办?
例如,我如何扫描以下 JSON 中的“Moby Dick”,同时找到与该标题相关的作者?
"store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
}
}
最佳答案
假设这是你的对象:
var store= {
"book": [
{...}, {...}
]
}
然后你可以尝试这样过滤:
var foundBooks = store.book.filter(function(book) { return book.title ==="Moby Dick"});
正如@JLRiche正确指出的那样,foundBooks
是一个数组。为了访问第一个匹配项,我们将采用与处理所有数组相同的方式:
var book = foundBooks[0];
关于javascript - 解析 JSON 以获取对象内的相关键/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24023410/