I have a locale object that looks like this
{
hello.title: {
en: "Hi",
sv: "Hej"
},
hello.text: {
en: "Hur mår du?",
sv: "How are you?"
},
}
function mapToNewObj(locale, obj) {
// Here I want to return a new object that looks like this
let's say the locale is "sv"
return {
hello.title: Hej,
hello.text: 'Hur mår du?'
}
}
I want to create a new object where the key is for example "hello.title" and the value is the string for the locale that is passed in as the first argument.
How should I do it?
return {
'hello.title': obj['hello.title'][locale],
'hello.text': obj['hello.text'][locale]
}
or through loop
result = {}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = obj[key][locale]
}
}
return result
let input = { 'hello.title': { 'en': "Hi", 'sv': "Hej" }, 'hello.text': { 'sv': "Hur mår du?", 'en': "How are you?" }, }; function mapToNewObj(locale, obj) { return { 'hello.title': input['hello.title'][locale], 'hello.text': input['hello.text'][locale] } } console.log(mapToNewObj('sv', input));
Using a generic approach you could
var Language = {
"hello.title": {
en: "Hi",
sv: "Hej"
},
"hello.text": {
en: "Hur mår du?",
sv: "How are you?"
},
}
;
// fn receives (value, key), returns a new value for key.
const mapKeys = (fn) => obj => Object.entries(obj)
.reduce((res, [k, v]) => ({...res, [k]: fn.apply(null, [v, k])}), {});
const get = (key) => obj => obj[key];
console.log(mapKeys(get("sv"))(Language));
mapKeys
takes a function fn
and returns a new function which takes an object. It returns an object with the same shape but with value produced by fn
. Here fn
is simply get
which just selects a given field inside an object.
You mean something like this?
var Language = {
en: {
title: 'hey',
text: 'Hur mår du?',
},
sv: {
title: 'hej',
text: 'How are you?',
},
};
// @param {string} locale The locale language return as "sv" or "en"
function returnLanguageMessage(locale) {
return {
Language[locale].title,
Language[locale].text
};
}
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.