niemax
niemax

Reputation: 29

Mapping throught an array with Objects

new to React Native, how would I go about getting values from this data Object. In JSX return statement, I'm mapping through the whole array and getting access to data.x and data.y, but how would I map through the "z" object to get the values for each key? For example "nimi": "Chest Fly" ("Chest Fly" would be the one needed in this case). Thank you in advance!

Array [
  Object {
    "x": "7. toukokuuta 2021",
    "y": "rintatreeni",
    "z": Object {
      "Chest Fly": Object {
        "nimi": "Chest Fly",
        "sarjat": 3,
        "toistot": 10,
      },
      "Dipit": Object {
        "nimi": "Dipit",
        "sarjat": 3,
        "toistot": "10-15",
      },
      "Penkkipunnerrus": Object {
        "nimi": "Penkkipunnerrus",
        "sarjat": 3,
        "toistot": 10,
      },
      "Punnerrukset": Object {
        "nimi": "Punnerrukset",
        "sarjat": 3,
        "toistot": "5-10",
      },
      "Pystypunnerrus": Object {
        "nimi": "Pystypunnerrus",
        "sarjat": 3,
        "toistot": "8-10",
      },
      "Tricep Pushdown": Object {
        "nimi": "Tricep Pushdown",
        "sarjat": 3,
        "toistot": 10,
      },
      "Vipunosto": Object {
        "nimi": "Vipunosto",
        "sarjat": 3,
        "toistot": 10,
      },
    },
  },
]

Here is my current code:

 <List.Section title="Tehdyt Treenit">
                   {
                       treenit.map((item, index) => {
                        
                           return(
                            
                        <List.Accordion key={index}
                        title={`${item.x} - ${item.y}`}
                        left={props => <List.Icon {...props} icon="folder" />}
                        >
                       {Object.keys(item.z).map(key,idx => {
                            return(
                            <List.Item key={idx} title={treeniData[key]} />
                            )
                        })} 
                     
                    </List.Accordion>
                               
                              
                           )
                       })
                   }
                   </List.Section>

"treenit" is an array state.

Upvotes: 0

Views: 90

Answers (1)

Jonathan Weibel
Jonathan Weibel

Reputation: 134

EDIT:

According to List.Item API https://callstack.github.io/react-native-paper/list-item.html I would write something like:

{Object.values(item.z).map(zItem => {
  let desc = `Sarjat: ${zItem.sarjat}, Toistot: ${zItem.toistot}`;
  return(
    <List.Item key={zItem.nimi} title={zItem.nimi} description={desc} />
  )
})}

ORIGINAL ANSWER:

You can use Object.values() to loop over the z object, e.g.

yourArray.map(item => {
  return Object.values(item.z).find(zItem => zItem.nimi === "Chest Fly");
})

Result:

[{
    "nimi": "Chest Fly",
    "sarjat": 3,
    "toistot": 10
}]

Upvotes: 2

Related Questions