Home > Mobile >  How to properly map through objects in react but only show a specific value
How to properly map through objects in react but only show a specific value

Time:04-14

A couple of days ago I asked a question with an issue I had from a return off a form. After not realizing out the I was trying to map an object I was able to map the object with this code:

{Object.entries(stats1).map(([key, value], i) => {
  return (
   <Text>{key} : {value}</Text>
  )
})}
// stats1 prop is set like this with the use of state
setStats1(response?.data.data.data.stats.all.solo)

however not in the way I'd like currently it renders like the first image below, How ever I want to exclude the key and just show a specific value with a specific key of my own such as Solo Kills Total: 5067 instead of kills: 5067. I this possible? Over the last couple of days I haven't been able to find a definitive answer that has resulted in the way I'd like.

Any help would be huge and greatly appreciated!

// Json response from stats1 prop
{
    "score": 52697,
    "scorePerMin": 22.932,
    "scorePerMatch": 16.545,
    "wins": 115,
    "top10": 623,
    "top25": 1163,
    "kills": 5067,
    "killsPerMin": 2.205,
    "killsPerMatch": 1.591,
    "deaths": 3070,
    "kd": 1.65,
    "matches": 3185,
    "winRate": 3.611,
    "minutesPlayed": 2298,
    "playersOutlived": 19072,
    "lastModified": "2022-04-10T13:52:22Z"
}

screnshot of issue

CodePudding user response:

Create a mapper object that maps your json keys to custom keys and use that object to render


const mapper = {
   kills: "Solo Kills Total"
}

{Object.entries(stats1).map(([key, value], i) => {
  return (
   <Text> {mapper[key] ? mapper[key] : key} : {value}</Text>
  )
})}

CodePudding user response:

Considering we are getting the data you want like this:

const obj = {
  "kills": 5067,
}

by something like this:

response?.data.data.data.stats.all.solo.kills //added kills

then we can rename kills like this:

delete Object.assign(obj, {SoloKillsTotal: obj.kills})['kills'];

console.log(obj);
  • Related