Bodrov
Bodrov

Reputation: 867

Rendering nested array object values into JSX element

I have a nested array of objects that looks something like this:

[
  {
    _Category: "Animals",
    _Child: {
       _Obj: [{_Title: "Monkey", _Link: "www.monkeys.com"}], [{_Title: "Monkey", _Link: "www.monkeys.com"}], etc
    }
  },
  {
    _Category: "Fruit",
    _Child: {
       _Obj: [{_Title: "Apple", _Link: "www.apples.com"}], [{_Title: "Pineapple", _Link: "www.pineapples.com"}], etc
    }
  }
]

I'm trying to append the _Title and _Link of each group into a JSX element. I've been able to render the _Categories without a problem, but the nested values are giving me a hard time.

When I go to the Elements in DevTools, I can see that there are 11 different groups for each item---which is how many array of objects there are under that particular category---but the _Titles and _Links are empty.

In the code below, I mapped through the _Category data and displayed the Categories that way. Do I have to do something similar for the _Child object---another map, maybe, or something else?


Code:

Element = ({ cats }) => {
    return (
        <div>
            {cats
                .filter((cat) => cat._Root === "Quick Links")
                .map((cat) => (
                    
                 <>
                  <div className={"colFor-" + cat._Category}>
                    <h5>{cat._Category}</h5>

                    {cat._Child._Obj.map((item) => (
                        <>
                            <a href={item._Link}>
                                <p>{item._Title}</p>
                            </a>
                            <br />
                        </>
                    ))}
                        
                   </div>
                  </>
                ))
            }
            
        </div>
    )
  }

Here's what cats looks like:

enter image description here


Update: As @Dominik pointed out, the way my obj was set up was incorrect so I changed it.

Upvotes: 1

Views: 85

Answers (1)

Eric
Eric

Reputation: 1347

According to your sample data, cat._Child._Obj is an array and each item in it is also an array, so I think you need to flat you array first then use the map function.

const myarr = [[{_Title: "Monkey1", _Link: "www.monkeys1.com"}], [{_Title: "Monkey2", _Link: "www.monkeys1.com"}]];
const myarrFlat = myarr.flat();
myarrFlat.map(cat => console.log(cat._Title, cat._Link));

Upvotes: 2

Related Questions