简体   繁体   中英

how to select the chosen object in JavaScript

This is my JavaScript object:

   {
    "login" : {
        "title" : "title1"
        "content1" : "content1"
        }
    "Menu" : {
        "title" : "title2"  
        }
    }

How do I get the value of of a property of the JavaScript object with function getvalue("login","title") or getvalue("login","content1") and return title1 or content1 ? I do this to make a multi-language phonegap apps so when the function called i compare with lang attribute in html, i use xui and pure javascript and no jquery becouse it's to heavy for phonegap i think.. can anyone help me? or is there any best method for multilanguage?

Your JSON

myJSON = { 
  'login' : { 'title' : 'title1'},
  'menu' : { 'title' : 'title2'} 
};

You can call the value like this:

alert(myJSON.login.title);

it will output: title1.

So assuming this is a standard json in a standard variable: var myJson. Why cant you return

myJson.login.title (per this syntax)

In the example above login is not an array so you wouldnt be able to return a list of login values

With regards to internationalization I would do something simpler (and I have been doing that successfully in my apps). Just create a set of name-value pairs in a file calls language.en.xml (or json etc depending if you can easily parse json or xml using your framework) and one called language.it.xml if lets say you wanted to have the italian language as well. Then each key (eg login) is the same for every file and the value is the title you want to have in each language. So pretty similar to yours but you dont need a hierarchy.

Then you can create a static method called Internationalize('Login') that will return the value of login for the language the user has chosen. So in your method you will check the users language settings and read the value from the required file. If language is IT then check value in language.it.xml (or json etc.) if default or NULL or en then check the english file.

Optimizations like pre-loading the language file contents in memory are also things you should be thinking about.

i found the answer finally, here it is :

var data = {
"login" : {
    "title" : "title1"
    "content1" : "content1"
    }
"Menu" : {
    "title" : "title2"  
    }
}

function getvalue(resource, paramA, ParamB) 
{
   return resource[paramA][paramB];
}

end then just called :

getvalue(data,"login","content1")

it will return content1

huff, finally i found this :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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