简体   繁体   中英

How to using array.prototype.join in reactjs

I want to join all the names by using space

 const { author} = this.props;
        const authors= author.map((e, i) =>
            <div className="ck12 o6 b4" key={i}>
                <div className="authorlist">
                    <h4>{e.name}</h4>

The code looks like this. JohnTomJack I want John Tom Jack. I added e.name.join(" ") but code giving error join is not a function. I try how to render react components by using map and join but I could not.

Good morning sir,

The function join is only applicable to an Array . Learn more about it here: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/join

THis function will join all the elements (in most of the cases, strings) from the array to a single string.

For your specific case since the author name is inside an object with the property name, you could do the following:

const authorNames = author.map(e => e.name).join(' ');
// authorNames will be now John Tom Jack

You will use the map method to transform that array to a new array containing only strings. Then you can join those strings with the join function.

 // Example class component class Thingy extends React.Component { render() { const names = [{ name: 'John'}, {name: 'Doe'}, {name: 'Snow'}]; console.log('names', names); return ( <div> <div>{names.map(e => e.name).join(' ')}</div> </div> ); } } // Render it ReactDOM.render( <Thingy />, document.getElementById("react") ); 
 <div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

Hope that helps.

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