简体   繁体   中英

React - Map through array of objects

I'm able to map data when just using an object, but when using an array it doesn't some to work.

No errors in command line just nothing outputted.

Help appreciated.

Thanks

import React from 'react';
import ReactDOM from 'react-dom';

class JoeApp extends React.Component {
    render() {
        var data = [
            {
                name: "Joe",
                age: 27
            },
            {
                name: "John",
                age: 27
            },
            {
                name: "Bill",
                age: 25
            }
        ];

        return (
            <Data data={data} />
        );
    }
}

class Data extends React.Component {
    render() {
        return (
            <div>{this.props.data.name.map((info) => info.name})}</div>
        );
    }
}

ReactDOM.render(<JoeApp />, document.body);

You need to use the .map() function on the array itself, which would be this.props.data :

<div>{this.props.data.map((elem) => elem.name})}</div>

This will convert the array of objects:

var data = [
        {
            name: "Joe",
            age: 27
        },
        {
            name: "John",
            age: 27
        },
        {
            name: "Bill",
            age: 25
        }
    ];

To an array of name strings:

var data = ["Joe", "John", "Bill"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM