gpt4 book ai didi

Javascript:将嵌套对象转换为具有值作为路径的对象

转载 作者:行者123 更新时间:2023-11-30 00:24:52 24 4
gpt4 key购买 nike

此问题不是 Fastest way to flatten / un-flatten nested JSON objects 的重复问题,因为附加值变成键,所以顺序发生很大变化,我的对象不仅仅是“在一行”。

我更新了问题描述以使其更清楚。


我有一个嵌套对象,它表示到 Controller 映射的多语言路径:

{
"welcome": {
"news": {
"de": "nachrichten",
"en": "news"
},
"de": "willkommen",
"en": "welcome"
},
"applications": {
"application1": {
"de": "anwendung1",
"en": "application1"
},
"application2": {
"features": {
"de": "funktionen",
"en": "features"
},
"de": "anwendung2",
"en": "application2"
},
"de": "anwendungen",
"en": "applications"
}
}

这应该被转换为一个易于使用的接受路径作为键的对象:

{
"/de/willkommen/": "welcome",
"/en/welcome/": "welcome",
"/de/willkommen/nachrichten/": "news",
"/en/welcome/news/": "news",
"/de/anwendungen/": "applications",
"/en/applications/": "applications",
"/de/anwendungen/anwendung1/": "application1",
"/en/applications/application1/": "application1",
"/de/anwendungen/anwendung2/": "application2",
"/en/applications/application2/": "application2",
"/de/anwendungen/anwendung2/funktionen/": "features",
"/en/applications/application2/features/": "features",

}

现在初始语言特定值(“de”:“willkommen”等)构建路径并且是键,初始键是值。但是请看一下,它有点复杂。

我已经构建了一个函数,但它们仅适用于第一级,如“/de/anwendungen/”,不适用于“/de/anwendungen/anwendung1/”及更低级别。

  convertToPath(OldObject, NewObject = {})
{
for(let SecondObject in OldObject)
{
for(let Key in OldObject[SecondObject])
{
NewObject["/" + Key + "/" + OldObject[SecondObject][Key] + "/"] = SecondObject;
}
}

return NewObject;
}

最佳答案

好吧,你可以通过使用递归遍历来创建你的对象数据树,像这样:

var data = {
"welcome": {
"news": {
"de": "nachrichten",
"en": "news"
},
"de": "willkommen",
"en": "welcome"
},
"applications": {
"application1": {
"de": "anwendung1",
"en": "application1"
},
"application2": {
"features": {
"de": "funktionen",
"en": "features"
},
"de": "anwendung2",
"en": "application2"
},
"de": "anwendungen",
"en": "applications"
}
};

var langs = ['en', 'de'];

var path_to_controller = function(data, paths, pathsofar){
paths = paths || {};
pathsofar = pathsofar || {};
Object.keys(data).forEach(function(key){
var newpathsofar;
if(langs.some(function(lang){ return key === lang; })){
return;
}
newpathsofar = langs.reduce(function(p, lang){
p[lang] = pathsofar[lang] || '/' + lang + '/';
p[lang] += data[key][lang] + '/';
paths[p[lang]] = key;
return p;
}, {});
path_to_controller(data[key], paths, newpathsofar)
});
return paths;
};

var paths = path_to_controller(data);
var pre = document.createElement('pre');
pre.innerHTML = JSON.stringify(paths, null, 4);
document.body.appendChild(pre);

您的嵌套对象似乎很难使用,所以我可以理解您想转换成另一种格式。或许您可以安排以更易于使用的格式提供路径数据。

编辑:推广到任意数量的语言。

关于Javascript:将嵌套对象转换为具有值作为路径的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31795907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com