1

I want to iterate over nested object and rendering out for each item an text element in react native.

const translationToWeekDays = {
fr_FR: {
  Monday: lundi,
  Tuesday: mardi,
  Wednesday: mercredi,
  Thursday: jeudi,
  Friday: vendredi,
},
};

This is the object, and this is my current code

          <>
            {Object.values(translationToWeekDays).forEach((week) => {
              Object.values(week).forEach((day) => (
                <Row>
                  <Text>
                    {day}
                  </Text>
                </Row>
              ));
            })}
          </>

any directions as to where i am going wrong? :(

0

3 Answers 3

1

Try something like this?

{Object.values(translationToWeekDays).map((week) =><> { Object.values(week).map((day) =>

{day}

)}</>)}

Sign up to request clarification or add additional context in comments.

1 Comment

To clarify, .forEach does not have a return value, so that is why .map works instead.
0

Cant make a comment but make sure to use map as it can return jsx...

const translationToWeekDays = [
[
  lundi,
  mardi,
  mercredi,
  jeudi,
  vendredi
],
];
<>
            {translationToWeekDays.map((week) => {
              Object.values(week).map((day) => (
                <Row>
                  <Text>
                    {day}
                  </Text>
                </Row>
              ));
            })}
          </>

5 Comments

Still not rendering out :(
Oh I misread your post.... you should be using an array not a nested object.. will update code
what you can do instead if you would like to use the map function is change this to an array and verify the dates by index
Can't i make it work without chaning the object? I would like to keep the object, there must be a way to render out in a loop with iterating over the nested object
are there other languages in the parent objcet?
0

To solve your problem, you can try this, can be a possible without changing the original object.

const translationToWeekDays = {
  fr_FR: {
    Monday: "lundi",
    Tuesday: "mardi",
    Wednesday: "mercredi",
    Thursday: "jeudi",
    Friday: "vendredi"
  }
};

export default function App() 
{

  let daysTranslation = []

  for (let day in translationToWeekDays.fr_FR) 
  {
    daysTranslation.push({
      id: day,
      value: translationToWeekDays.fr_FR[day]
    })
  }


  const daysTranslated = daysTranslation.map(item =>
    {
      return <Text>{item.value}</Text>
    })



  return (
    <Row>
      {daysTranslated}
    </Row>
  );
}

However, using Flatlist better than mapping. But this should work for a small list. To loop over content, transforming object into map is the best idea

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.