问题描述
我有一个JSON数据,我想自动查找每次出现的特定名称.
I have a JSON data, that I want to automatically find every occurrence of a specific name.
{
"servergenre": "Classic Rock",
"servergenre2": "pop",
"servergenre3": "rock",
"servergenre4": "jazz",
"servergenre5": "80s",
"serverurl": "http://www.name.com",
"servertitle": "ServerHero",
"bitrate": "48",
"samplerate": "0"
}
在这里servergenre
用增量(2,3,4,5 and ...
)重复了几次,因为我不知道JSON中会有多少servergenre
,我需要一种方法来遍历它并查找多次因为存在servergenre
的实例,并可能将结果添加到数组中.
in here servergenre
is repeated a few times with increment (2,3,4,5 and ...
) as I do not know ho many servergenre
there will be in the JSON, I need a method to loop through it and find as many times as there are instances of servergenre
and add the result in an array possibly.
类似下面的代码:
var URL = "http://name.com/file.json"
$.getJSON(URL, function(data) {
var i = 1;
$.each(data.servergenre + i, function(index, value) {
/// CODE
});
});
显然上面的代码不起作用,但这是我的最初想法.
Obviously the code above does not work but that was my initial idea.
那么有什么更好的主意可以使其工作并将servergenre
的所有现有实例保存在数组中?
So any better idea to make it work and save all exisiting instances of servergenre
in an array?
谢谢.
推荐答案
测试JSON中的每个键,看是否与"servergenre"匹配.如果是这样,则将相应的值推入数组.
Test each key of your JSON to see if it matches "servergenre". If it does, push the corresponding value to an array.
let json = {
"servergenre": "Classic Rock",
"servergenre2": "pop",
"servergenre3": "rock",
"servergenre4": "jazz",
"servergenre5": "80s",
"serverurl": "http://www.name.com",
"servertitle": "ServerHero",
"bitrate": "48",
"samplerate": "0"
}
let result = []
Object.keys(json).forEach( key => {
if(/servergenre/.test(key)) result.push(json[key])
})
console.log(result) // ["Classic Rock","pop", "rock","jazz","80s"]
带有过滤器和地图的替代方法(由osynligsebastian的答案启发):
Alternative method (inspired by osynligsebastian's answer) with filter and map :
let json = {
"servergenre": "Classic Rock",
"servergenre2": "pop",
"servergenre3": "rock",
"servergenre4": "jazz",
"servergenre5": "80s",
"serverurl": "http://www.name.com",
"servertitle": "ServerHero",
"bitrate": "48",
"samplerate": "0"
}
let result = Object.keys(json)
.filter( key => /servergenre/.test(key))
.map( key => json[key] )
console.log(result) // ["Classic Rock","pop", "rock","jazz","80s"]
这篇关于如何搜索JSON并查找每个出现的特定名称(带有增量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!