Home > Net >  JavaScript: get values data from Destructuring of objects
JavaScript: get values data from Destructuring of objects

Time:08-29

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}`];
  });

CodePudding user response:

You can make it more dynamic with a modified 'group-by'. Here using a regex with named capturing groups to isolate the category and language and then grouping into an object keyed by category.

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 translationCategories = {};
for (const [key, value] of Object.entries(translations)) {
  const { category, language } = key.match(/snippet(?<category>\w )_(?<language>\w )/).groups;

  const translationCategory = (translationCategories[`${category.toLowerCase()}Translations`] ??= {});
  translationCategory[language] = value;
}

console.log(translationCategories);

CodePudding user response:

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

  • Related