skip to Main Content

a have array like this

array = [{name : john , age:20},{name : jack, age:24},{name : rose, age:26},{name : 
david, age:40}]

the array.length is 4 and i wanna mapped in react like this

array.map((list)=>(
<h1>{list.name}</h1>
<h2>{list.age}</h2>
)) 

but i wanna mapped to first two object in array like array.lentgh = 2
and gets output like this

<h1>john</h1>
<h2>20</h2>

<h1>jack</h1>
<h2>24</h2>

because i wanna mapped two other object some where else
how to do that

2

Answers


  1. Use Array.slice:

    The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

    Note 1: your name values in your objects must be in quotes.

    Note 2: inside your mapped data your markup needs to be wrapped in either a containing element or a React fragment.

    Note 3: ideally you want to add an id to your objects that you can use as a key on the wrapping element (rather than using the map index).

    const { useState } = React;
    
    function Example({ data }) {
      return (
        <main>
          {data.slice(0, 2).map(obj => {
            return (
              <section key={obj.id}>
                <h1>{obj.name}</h1>
                <h2>{obj.age}</h2>
              </section>
            );
          })} 
        </main>
      );
    }
    
    const data = [{id:1,name:'john',age:20},{id:2,name:'jack',age:24},{id:3,name:'rose',age:26},{id:4,name:'david',age:40}];
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Example data={data} />);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
    <div id="root"></div>
    Login or Signup to reply.
  2. I see, this is more like a programming thing, there’s lots of ways. Other than the slice, which could be the best safe way. If you just start programming, you can try the following as well.

    [0,1].map(i => ( 
      <>
        <h1>{array[i].name}</h1>
        <h2>{array[i].age}</h1>
      </>
    ))
    

    As I said, this is programming, do whatever to make it work then. For example, just copy paste twice that’ll solve your problem as well. Or do a loop and skip when index is bigger than two.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search