user1752759
user1752759

Reputation: 643

Iterate through nested object that are dynamic

I have the following list:

const list = [
    {
        id: '1',
        task: 'task 1',
        activities: [{
            'swimming': false,
            'tennis': false,
            'football': false,
            'basketball': false
        }],
        allCompleted: false
    },
    {
        id: '2',
        task: 'task 2',
        activities: [{
            'soccer': false,
            'rugby': false,
            'golf': false,
            'baseball': false
        }],
        allCompleted: false
    },
    {
        id: '3',
        task: 'task 3',
        activities: [{
            'hockey': false,
            'netball': false,
            'softball': false,
            'surfing': false
        }],
        allCompleted: false
    }
];

However, when I use:

<ul>
    {list.map(item => (
        <li key={item.id}>
           {item.task}
           <ul>
               <li>{item.activities}</li>
           </ul>
        </li>
    ))}
</ul>

I get a Objects are not valid as a React child error.

I am trying to iterate through the list to display the task name and any activities that go with it:

How can I produce the output above?

I'll be using the false/true value on each activity later for when the user has selected an item in the list.

Upvotes: 0

Views: 66

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281726

You get an error because item.activities is an array of object and you can't render an object directly.

Instead you need to loop over object keys

<ul>
    {list.map(item => (
        <li key={item.id}>
           {item.task}
           <ul>
               {Object.keys(item.activities[0]).map(act => <li>{act}</li>)}
           </ul>
        </li>
    ))}
</ul>

Upvotes: 3

Related Questions