user3476614
user3476614

Reputation: 607

Mapping object values from one object to another

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?

Upvotes: 0

Views: 1917

Answers (4)

adz5A
adz5A

Reputation: 2032

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.

Upvotes: 1

Nicholas Gew
Nicholas Gew

Reputation: 33

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
  };
}

Upvotes: 0

curlyBraces
curlyBraces

Reputation: 1105

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));

Upvotes: 1

Dmitrii G.
Dmitrii G.

Reputation: 895

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

Upvotes: 1

Related Questions