V
V
vaech2021-03-05 18:45:32
React
vaech, 2021-03-05 18:45:32

How to iterate over an object and change certain values?

Good day! There is an object with some data. For example:

const data = {
    title: 'title',
    description: 'description',
    address: {
      city: 'city',
      street: 'street',
    },
  };


And there is a second object containing translations of individual values ​​of the data object:
const translation = {
    title_en: 'title_en',
    title_fr: 'title_fr',
    city_en: 'city_en',
    city_fr: 'city_fr',
    description_en: 'description_en',
    description_fr: 'description_fr',
  };


The default language is English, and the child component receives a data object, but if the user switches the language, then the value of individual fields in the data object must be replaced with the equivalent from the translation object. That is, as a result of the transformation, the new object based on data should look something like this:

const data_french = {
    title: 'title_fr',
    description: 'description_fr',
    address: {
      city: 'city_fr',
      street: 'street',
    },
  };


How can you iterate over the data object and replace only those values ​​that are in the translation object, given the possibility of nesting?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2021-03-05
@Casufi

https://developer.mozilla.org/en-US/docs/Web/JavaS...
https://en.wikipedia.org/wiki/%D0%A0%D0%B5%D0%BA%D.. But isn't it easier to use https://github.com/i18next/react-i18next
Object[key] = translation[key+"_"+lang]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question