Home > Software engineering >  Failing to map property values in React.js and Typescript
Failing to map property values in React.js and Typescript

Time:06-11

I'm quite new to React and Typescript. I do have an object that has property values as arrays.I can get the object's value through the below logic.

  let cityObj =   {
              "Harare":[
                        {
                        "released_on":"2007-11-08T00:00:00",
                        "slug":"0985"
                       },
                       {
                        "released_on":"2007-11-08T00:00:00",
                        "slug":"2346"
                       }
                      ],
               "bulawayo":[
                        {
                      "released_on":"2007-11-08T00:00:00",
                      "slug":"9383"
                    }
                 ]
             }

  Object.keys(cityObj).forEach(el =>{
     console.log(cityObj[el]);
  })

The output is as follows;

array(3)
array(1)

This is what i'm seeking to do in them jsx react return function. By i'm only getting the city name e.g Harare and Bulawayo after using the code below.

{Objects.keys(cityObj).map((city:any) =>
      <div> {city}  
         cityObj[city].map((el:any) =>  <span>- {el.slug}</span>)
      </div>
 )}

What I really want is something like this:

Harare
  -0985
  -2345
Bulawayo
  -9383

But in this case, I'm only getting city names and the city data is not showing.

CodePudding user response:

seems you just forget to pass inside map to a react executable code block

{Objects.keys(cityObj).map((city:any) =>
      <div> {city}  
         {cityObj[city].map((el:any) =>  <span>- {el.slug}</span>)}
      </div>
 )}
  • Related