简体   繁体   中英

How to display key and value from array in Text in React Native?

I'm trying to map/loop through my array, so I can display every key and value on my mobile app screen.

This is my array

const getExpense = [{"fecha": "09", "text": "Comida", "value": 2896}, {"fecha": "09", "text": "Misc", "value": 1714}, {"fecha": "09", "text": "Transporte", "value": 1525}, {"fecha": "09", "text": "Salida", "value": 1260}, {"fecha": "09", "text": "Deporte", "value": 560}, {"fecha": "09", "text": "Farmacia", "value": 367}, {"fecha": "09", "text": "Pulperia", "value": 126}, {"fecha": "09", "text": "Ayuda", "value": 50}]

I did some research and this is the function I found that could work for me to map over every object. It should work with just 1 item. But I have 3 items: fecha, text and value.

function display(){
        return getExpense.map((item,item1,item2)=>{
            return(
                <RN.Text>
                    {item} {item1} {item2}
                </RN.Text>
            )
        })
    }

And here's my RN code to return the Display function. I also tried to return it in a but that didn't work out.

return(
    <RN.View>
        <RN.Text>
              {display()}
        </RN.Text>
    </RN.View>
)

And it's giving me this problem:

Render Error: Objects are not valid as a React Child (Found: an object with keys {fecha, text, value}. If you meant to render a collection of children, use an array instead.

Any help will be greatly appreciated.

I was able to fix it.

I changed my function to the objects key names, so instead of item, item1, item2, I used value and text (Name of my keys).

Please take a look for anyone who'se having the same problem.

function display(){
    return getExpense.map(({text, value})=>{
        return(
            <RN.Text>
                {text} : {value}
            </RN.Text>
        )
    })
}
    const getExpense = [{"fecha": "09", "text": "Comida", "value": 2896}, {"fecha": "09", "text": "Misc", "value": 1714}, {"fecha": "09", "text": "Transporte", "value": 1525}, {"fecha": "09", "text": "Salida", "value": 1260}, {"fecha": "09", "text": "Deporte", "value": 560}, {"fecha": "09", "text": "Farmacia", "value": 367}, {"fecha": "09", "text": "Pulperia", "value": 126}, {"fecha": "09", "text": "Ayuda", "value": 50}]

function display(){
        return getExpense.map((obj)=>{
            return(
                <RN.Text>
                  {Object.entries(obj).map(([key, value]) => `${key}: ${value}`).join(' ,')}
                </RN.Text>
            )
        })
    }
    
    console.log(display())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM