Skip to content
Advertisement

JavaScript: get values data from Destructuring of objects

I have this data set:

const data = {
    prop1: 'z',
    prop2: 'x',
    prop3: 'y',
    snippetItem_en: "abc",
    snippetItem_fr: "def",
    snippetCar_en: "123",
    snippetCar_fr: "456",
}

I take the translations out of it like this:

const {prop1, prop2, prop3, ...translations} = data;

But I would like to convert this received result in translations into such a result:

const carTranslations = {en: '123', fr: '456'};
const itemTranslations = {en: 'abc', fr: 'def'};

So far I have achieved this effect through such a petticoat, but I am convinced that it can be done better.

const carTranslations = {};
const itemTranslations = {};


  ['en', 'fr'].forEach((language) => {
    carTranslations[language] = translations[`snippetCar_${language}`];
    itemTranslations[language] = translations[`snippetItem_${language}`];
  });

Advertisement

Answer

This solution uses Array.reduce() to implement a sorting algorithm. Destructuring is used to get the same named constants from your example code.

const data = {
  prop1: 'z',
  prop2: 'x',
  prop3: 'y',
  snippetItem_en: "abc",
  snippetItem_fr: "def",
  snippetCar_en: "123",
  snippetCar_fr: "456",
}

const {
  prop1,
  prop2,
  prop3,
  ...translations
} = data;

const {
  carTranslations,
  itemTranslations
} = Object.entries(translations).reduce((result, [key, value]) => {
  const [phrase, lang] = key.replace('snippet', '').toLowerCase().split('_');
  result[phrase + 'Translations'] ??= {};
  result[phrase + 'Translations'][lang] = value;
  return result;
}, {});


console.log(carTranslations);
console.log(itemTranslations);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement