How to map an array of objects in React

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

An array of objects that I want to display:

const theData = [
    {
        name: 'Sam',
        email: 'somewhere@gmail.com'
    },

    {
        name: 'Ash',
        email: 'something@gmail.com'
    }
]

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?

+4
source share
4 answers

What you need to map an array of objects and remember that each element will be an object, so you will use, for example, dot notation to take the values ​​of the object.

In your component

 [
    {
        name: 'Sam',
        email: 'somewhere@gmail.com'
    },

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

, jsx, , , .

jsx

+7

, :

const renObjData = this.props.data.map(function(data, idx) {
    return <p key={idx}>{data.name}</p>;
});

:

const renObjData = this.props.data.map(function(data, idx) {
   return ([
       <p key={idx}>{data.name}</p>,
       <p key={idx}>{data.email}</p>,
   ]);
});
+2

try the following snippet

const renObjData = this.props.data.map(function(data, idx) {
    return <ul key={idx}>{$.map(data,(val,ind) => {
        return (<li>{val}</li>);
    }
    }</ul>;
});
0
source

@FurkanO provided the right approach. Although for a cleaner approach (es6 way) you can do something like this

[{
    name: 'Sam',
    email: 'somewhere@gmail.com'
 },
 {
    name: 'Ash',
    email: 'something@gmail.com'
 }
].map( ( {name, email} ) => {
    return <p key={email}>{name} - {email}</p>
})

Hooray!

0
source

Source: https://habr.com/ru/post/1663166/


All Articles