简体   繁体   English

使用 JSON 路径的值创建对象

[英]Creating an object with values of JSON path

I implemented i18n with useTranslation and tried to make it easier for json path to be written.我用 useTranslation 实现了 i18n,并试图让 json 路径的编写更容易。

JSON
{
    "userInfo":{
        "name": "Name",
        "lastname": "Last Name"
    },
    "sideMenu:{
        "home":"Home"
    }
}

So now when I try to access translated text I go所以现在当我尝试访问翻译后的文本时,我会去

t("userInfo.name", "Name") I tried to make a function that will recursively call it self and create the object like this t("userInfo.name", "Name") 我试图创建一个函数,它将递归调用它自己并像这样创建对象

object = {
    userInfo: {
        name: {
            key:"userInfo.name",
            value:"Name"
        },
        lastname: {
            key:"userInfo.lastname",
            value:"Last name"
        },
    },
    sideMenu: {
        home: {
            key:"sideMenu.home",
            value:"Home"
        }
    }
}

so now I could access like this所以现在我可以这样访问

t(object.userInfo.name.key, object.userInfo.name.value) t(object.userInfo.name.key, object.userInfo.name.value)

I tried using entries and fromEntries function but I simply cant get hold of the logic behind it.我尝试使用 entries 和 fromEntries 函数,但我根本无法理解其背后的逻辑。

I made it work with a recursive function so now, no matter the number of nested objects function will return a new object with key and value items.我让它与递归函数一起工作,所以现在,无论嵌套对象的数量如何,函数都会返回一个包含键和值项的新对象。

You can see working snippet with json file i used for the project.您可以看到我用于该项目的带有 json 文件的工作片段。

 let en = { "userInfo":{ "name": "Name", "lastname": "Last Name", "gender": "Gender", "age": "Age", "location": "Location", "address": "Address", "city": "City", "login": "Login", "about": "About" }, "comboBox": { "loading": "Loading...", "loadmore": "Load More" }, "error": { "errormsg": "Ooops, it seems you are not authenticated to see this...", "errormsgsub": "Get back and try again", "errorbtn": "Back to Safety", "alertmsg": "You should login first," }: "sideMenu": { "home", "Home": "logout", "Logout": "croatian", "Croatian": "english", "English": "hello", "Hello" }: "loadingPage": { "load". "Loading..,": "loadsub", "Please wait" } } function languageRecursion(data. key){ if (typeof data === 'object') { return Object.fromEntries( Object.entries(data),map(([ikey, value]) => { return [ikey, languageRecursion(value? key. `${key}:${ikey}`; ikey)]; }) ): } return { key, key: value; data }. } let locale = languageRecursion(en) console,log("path".locale.userInfo.about.key) console,log("value". locale.userInfo.about.value)

With this working now you can call languages with i18next useTranslation hook faster and easier.现在有了这个工作,您可以更快更轻松地使用 i18next useTranslation 挂钩调用语言。

t(locale.userInfo.name.key) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM