Search code examples
reactjsarraysjson

How to access a nested array inside of an API JSON response using React?


I am currently having troubles accessing the valus inside a nested array return from my API call. My API repsonse is being ran through a couple filters prior to being passed to the table as the variable "dataPagedSortedAndFiltered"

when I run a console.log 'console.log("Parameters: ", dataPagedSortedAndFiltered());, my data comes back in this format:

Parameters: 
    [{…}]
        0: 
            id: 33
            name: Upper Limits
            value: 1500
            ltm: Array(1)
                0: {ltmId: 104, ltmNumber: 3468}
                1: {ltmId: 110, ltmNumber: 3666}            
            type: Standard

I can easily access the id, name, value, and type values, but regardless whatever I tried to access the LTM values, I keep getting errors. I am wanting to map through the ltmNumbers and display them in a comma separated list.

I have tried multiple ways to access the data, including calling to items["ltm"]["ltmNumber"], but to no avail.

here is my table so you can see how I am attempting this:

return (
    <TableContainer>
        <TableBody>
            dataPagedSortedAndFiltered().sort((a, b) => (a.name.toLowerCase() > b.name.toLowerCase()) ? 1 : -1).map((item, id) => (
            <TableRow key={item.id} >
                <TableCell>Name: {item.name}</TableCell>
                <TableCell>Value: {item.value}</TableCell>
                <TableCell>Type: {item.type}</TableCell>
                <TableCell>
                    {(() => {
                        if ((item.ltm).length === 0) { return ("None"); }
                        else {
                        return (
                        {item.ltm.map((item: any, index: React.Key ) ltm => (
                            <span key={index} > 
                                {ltm.ltmNumber}{index !== (item.ltm.ltmNumber).length - 1 ? ', ' : ''}
                            </span>);
                        }
                    })()}
                </TableCell>
            </TableRow>
        </TableBody>
    </TableContainer>
  );

can someone please show me what I am doing wrong so I can display a list of ltmNumbers?


Solution

  • you can do it like this :

                <TableCell>
                    {item.ltm.length === 0 ? (
                        "None"
                    ) : (
                        item.ltm.map((ltm, index) => (
                            <span key={index}>
                                {ltm.ltmNumber}
                                {index !== item.ltm.length - 1 ? ', ' : ''}
                            </span>
                        ))
                    )}
                </TableCell>