0

i'm pretty new to react and javascript and i want to know how to iterate a list inside another list.

I have this json variable:

this.state = {
            groups: [{
                name: '',
                permission: [{
                    name: ''
                }]
            }]
        }

What I want to do is to count the number of elements the second list has, i did this following code but it sends the follwoing error, groups.map is not a function:

render() {

    let permissionGroup = this.state.groups.map((groups) => {
        let x = 0;
        groups.map((permission) => {
            x++;
        })
    })


    return (
              <div>

                    {this.state.groups.map((groups) => {
                    return (<li key={groups.code}>
                        <Card style={{ width: '20rem' }}>
                            <Card.Body>
                                <Card.Title>{groups.name}</Card.Title>
                                <Card.Subtitle className="mb-2 text- enter code heremuted">Permissions info</Card.Subtitle>
                                <Card.Text>
                                    This group has {permissionGroup}  permissions in it.
                             </Card.Text>
                                <Card.Link href="#">Add Permission</Card.Link>
                                <Card.Link href="#">Remove Permission</Card.Link>
                            </Card.Body>
                        </Card>
                    </li>)

                })}


              </div>
Book Of Zeus
  • 49,509
  • 18
  • 174
  • 171
jose azevedo
  • 245
  • 2
  • 3
  • 19
  • Are you sure your state is initially set to an array? Perhaps it is set afterwards via an asynchronous call. `.map()` is definitely a function on an array. The only way you would get this error is if the state hasn't been initialized yet, or it has been overwritten with a non array. – Blue Mar 15 '19 at 22:08
  • I think is very well explained here https://stackoverflow.com/questions/31676135/javascript-map-is-not-a-function/31676221 – calm Mar 15 '19 at 22:17

1 Answers1

0

Inside your first map, it should be groups.permission.map, not groups.map.

    let permissionGroup = this.state.groups.map((groups) => {
        let x = 0;
        groups.permission.map((permission) => {

That's because your first map is defining each "groups" as this:

{name: '', permission: [{name: ''}]}

So groups in this sense is an object, not an array. Access permission to get to the array you want.

Craig Gehring
  • 3,067
  • 1
  • 9
  • 11