Home > Software design >  Getting common array values from array.map() in React
Getting common array values from array.map() in React

Time:10-15

For example, I have array:

    [{subject:"farm",name:"John Doe"},
     {subject:"steam",name:"Michael Buck"},
     {subject:"geo",name:"Ron Ruckle"}, 
     {subject:"geo",name:"Ben Bond"}];

And this code would do the trick to fetch all names:

{user.map((item,key)=>
   { return
      <tr key={key}>
       <td>{user.name}</td>
      </tr>
 })}

I want to fetch only those usernames who have subject="geo". How can I do it?

CodePudding user response:

You can add a .filter():

{users
  .filter((user) => user.subject === 'geo')
  .map((user, index) => (
  <tr key={index}>
    <td>{user.name}</td>
  </tr>
)}

Or return null inside your map:

{users.map((user, index) =>
  user.subject === 'geo' ? (
    <tr key={index}>
      <td>{user.name}</td>
    </tr>
  ) : null
}

CodePudding user response:

It would be as simple as this.

{users.map((user,key)=> { 
  if (user.subject === "geo") {
    return (
        <tr key={key}>
         <td>{user.name}</td>
        </tr>
    );
  }
 })}

Edited: Changed your variable names to be more proper

  • users is the array of users. when we map each element in the users array is a user;

CodePudding user response:

I wouldn't use tables for coding your UI. Use table only for tabular displays. for everything else use div. Also, if you use a condition statement, you are forcing the DOM to evaluate every option in your array to be equal to "geo". In a small DB, no problme. When you have thousands or millions of values, not so great.

Better to programmatically filter through the prop before you send it to the DOM

Here's my option

export default function App() {

  const people = [
    {subject:"farm",name:"John Doe"},
    {subject:"steam",name:"Michael Buck"},
    {subject:"geo",name:"Ron Ruckle"}, 
    {subject:"geo",name:"Ben Bond"}
  ];
  
  const results = people.filter(obj => {
    return obj.subject === "geo";
  });


  const list = results.map((item) => {
    return (
      <p>{item.subject}, {item.name}</p>
  )})
  return (
    <div> {list} </div>
  )

}

CodePudding user response:

How about this?

{users.filter(user=>user.subject === 'geo').map((item,key)=>
      <tr key={key}>
       <td>{item.name}</td>
      </tr>
 )}
  • Related