How to map an array of objects in React

user3622460 picture user3622460 · Dec 7, 2016 · Viewed 141.4k times · Source

I have an array of objects. I would like to map this array of objects. I know how to map an array, but can't figure out how to map an array of objects. Here is what I have done so far :

The array of objects I want to map :

const theData = [
    {
        name: 'Sam',
        email: '[email protected]'
    },

    {
        name: 'Ash',
        email: '[email protected]'
    }
]

My component :

class ContactData extends Component {
    render() {
        //works for array
        const renData = this.props.dataA.map((data, idx) => {
            return <p key={idx}>{data}</p>
        });

        //doesn't work for array of objects
        const renObjData = this.props.data.map(function(data, idx) {
            return <p key={idx}>{data}</p>
        });

        return (
            <div>
                //works
                {rennData}
                <p>object</p>
                //doesn't work
                {renObjData}
            </div>
        )
    }
}


ContactData.PropTypes = {
    data: PropTypes.arrayOf(
        PropTypes.obj
    ),
    dataA: PropTypes.array
}

ContactData.defaultProps = {
    data: theData,
    dataA: dataArray
}

What am I missing ?

Answer

FurkanO picture FurkanO · Dec 7, 2016

What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.

In your component

 [
    {
        name: 'Sam',
        email: '[email protected]'
    },

    {
        name: 'Ash',
        email: '[email protected]'
    }
].map((anObjectMapped, index) => {
    return (
        <p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
            {anObjectMapped.name} - {anObjectMapped.email}
        </p>
    );
})

And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.

Take a look at my answer at mapping an array to jsx