我正在研究一个reactjs项目 - 在那里我说了一个英文网址,比如" / en / how-it-works"并希望遍历json树以找到设置此链接的位置/子级别 - 并找到其德语匹配对。
所以基本上 - 一个给出英文网址的函数,返回德国网址
所以 -
lng - 返回de currenlang - en pairUrl - / en / how-it-works
return / de / anleitung
或
lng - 返回en Currentlang de pairUrl - / de / beliebte-projekte / bundle1
return / en / popular-projects / bundle1
//功能
getLanguagePair (lng, currentLng, pairUrl) {
// 'find url in json tree'
console.log('linkTreeObject', linkTreeObject.langs)
var obj = {}
//find position in tree
if(currentLng === 'de'){
obj = linkTreeObject.langs[0].lines.menu
} else {
obj = linkTreeObject.langs[1].lines.menu
}
var pos = []
for (var k in obj) {
if (!obj.hasOwnProperty(k)) continue
if (obj[k].link === pairUrl) {
pos[k]
}
}
console.log('pos' , pos)
if (lng === 'de') {
return '/de/link'
} else {
return '/en/link'
}
}
// json file
{
"langs" : [
{
"lang" : "de",
"lines" : {
"menu" : [
{
"title": "Anleitung",
"link": "/de/anleitung",
"children" : []
},
{
"title": "Beliebte Projekte",
"link": "/de/beliebte-projekte",
"children" : [
{
"title" : "Bundle1",
"link" : "/de/beliebte-projekte/bundle1"
},
{
"title" : "Bundle2",
"link" : "/de/beliebte-projekte/bundle2"
}
]
}
],
"sign_in" : "Login"
}
},
{
"lang" : "en",
"lines" : {
"menu" : [
{
"title": "How it works",
"link": "/en/how-it-works",
"children" : []
},
{
"title": "Popular Projects",
"link": "/en/popular-projects",
"children" : [
{
"title" : "Bundle1",
"link" : "/en/popular-projects/bundle1"
},
{
"title" : "Bundle2",
"link" : "/en/popular-projects/bundle2"
}
]
}
],
"sign_in" : "Sign in"
}
}
]
}
答案 0 :(得分:1)
你必须循环使用' en'和' de'同时使用递归,因为你有嵌套链接。这是我的版本。我已经拿出了' en'和' de'数组并在函数中使用它们。
var obj ={
"langs" : [
{
"lang" : "de",
"lines" : {
"menu" : [
{
"title": "Anleitung",
"link": "/de/anleitung",
"children" : []
},
{
"title": "Beliebte Projekte",
"link": "/de/beliebte-projekte",
"children" : [
{
"title" : "Bundle1",
"link" : "/de/beliebte-projekte/bundle1"
},
{
"title" : "Bundle2",
"link" : "/de/beliebte-projekte/bundle2"
}
]
}
],
"sign_in" : "Login"
}
},
{
"lang" : "en",
"lines" : {
"menu" : [
{
"title": "How it works",
"link": "/en/how-it-works",
"children" : []
},
{
"title": "Popular Projects",
"link": "/en/popular-projects",
"children" : [
{
"title" : "Bundle1",
"link" : "/en/popular-projects/bundle1"
},
{
"title" : "Bundle2",
"link" : "/en/popular-projects/bundle2"
}
]
}
],
"sign_in" : "Sign in"
}
}
]
};
var en = obj.langs[1].lines.menu;
var de = obj.langs[0].lines.menu;
function GetUrl(enUrl, enMenu, deMenu)
{
var deUrl;
for(var i = 0; i < enMenu.length; i++)
{
if(enMenu[i].link == enUrl)
{
deUrl = deMenu[i].link;
break;
}
else
{
if(enMenu[i].children && enMenu[i].children.length > 0)
{
deUrl = GetUrl(enUrl,enMenu[i].children, deMenu[i].children )
}
}
}
return deUrl;
}
console.log(GetUrl("/en/how-it-works", en, de));
console.log(GetUrl("/en/popular-projects", en, de));
console.log(GetUrl("/en/popular-projects/bundle1", en, de));
console.log(GetUrl("/en/popular-projects/bundle2", en, de));
&#13;