Reputation: 47
Would like to handle translation with json and jquery. The problem i'm facing is how to get values and output its parameter if no such translation value exists.
Hard to explain, will try.
dict['Total Amount'] would for example return "My total amount" in another language, if that is what the key holds. But if I would send dict['Max Score'] and key "Max Score" doesn't exist it should write Max Score instead.
I have no idea how to accomplish this. Perhaps a json object would work? Really need help thanks.
Upvotes: 0
Views: 145
Reputation: 40639
Its array
not json object
and you had not added key Max Score
in dict
array, try to assign
Max Score key
like,
var dict=[];
dict['Total Amount'] ='My total amount';
alert(dict['Total Amount'] ,dict['Max Score']);// dict['Max Score'] = blank/undefined
dict['Max Score'] ='Max Score';
alert(dict['Max Score']);// alerts Max Score
If you use json
and get any key
by .
then don't use space
in a key, otherwise you can't be able to get the appropriate result.
Upvotes: 0
Reputation: 817128
How you store your data, e.g. as JSON, doesn't matter for this problem. Assuming you are having an object, such as
var de = {
'hello': 'hallo'
};
for a language, you can create a function that accepts a dictionary and a phrase to look up. Test if the phrase exists and if it doesn't, return the phrase itself:
function lookup(phrase, dict) {
if (dict.hasOwnProperty(phrase)) {
return dict[phrase];
}
return phrase;
}
var translation = lookup('bye', de);
References: Object#hasOwnProperty
, Working with Objects
Upvotes: 1