【发布时间】:2017-03-01 22:39:48
【问题描述】:
我想按国家/地区对输入的 JSON 进行分组,并输出按字母顺序排序的国家列表,并按字母顺序列出每个国家/地区的州名称。
//I would like the expected output in alphabetically sorted order in country
// and if the country has more than 1 state, the state should be in sorted order as follows:
var res=[
{
"country": "A", "state": "aa",
"country": "A", "state: "ca",
"country": "B", "state": "aa",
"country": "B", "state": "ca",
"country": "C", "state": "bb",
"country": "C", "state": "cb"
}
]
// GIVEN input variable in JSON format
var input = [{
"country": "A",
"state": "aa",
"information": [
{
"country": "B",
"state": "aa"
},
{
"country": "C",
"state": "bb"
},
{
"country": "C",
"state": "cb",
"information": [
{
"country": "A",
"state": "ca"
},
{
"country": "B",
"state": "ca"
}
]
}
]
}];
// 我尝试了以下递归函数,因为似乎可能有超过 1 个嵌套函数来获取信息。我试图 console.log 预期的输出,但它没有输出我想要的结果:
var res=[];
console.log(compare(input,0));
function compare (input, n) {
if(!input[0].information) return res;
for(i=0; i<n; i++){
res.push(
{
country: input[i].country,
state: input[i].state
}
)
}
console.log("res"+res[0]);
return compare(input[0].information, input[0].information.length)
}
【问题讨论】:
标签: javascript json sorting recursion nested