Home > other >  Displaying only one key value pair using .map in reactjs
Displaying only one key value pair using .map in reactjs

Time:10-15

I'm new to React JS. I'm trying to display the name key-value pair for each object in my array. Each object has 2 keys, and currently, when I run my project, it displays the name duplicated. I just want to remove the second display, and only map the name for each object to the console, the URL is simply a href. Here's my component:

export default function JSArticles() {
  return <List>
    {NEXT_JS_COOL_SITES?.map((info) => {
      return Object.keys(info).map((index) => (  
         <ListItem key={index}><a href={info.url}><Typography>{info.name}</Typography></a></ListItem> 
      ))      
    })}
  </List>
}

Here is the current output: project output

And for reference, here is my object list:

const NEXT_JS_COOL_SITES = [
  {
    name: "Next.js Blog",
    url: "https://nextjs.org/blog"
  },
  {
    name: "Awesome React Components to take a look at",
    url: "https://github.com/brillout/awesome-react-components"
  },
  {
    name: "Building IOS and Android Apps with React",
    url: "https://reactnative.dev/"
  },
  {
    name: "React Conference Talks on Youtube",
    url: "https://www.youtube.com/results?search_query=react conference talks"
  }
]

CodePudding user response:

You don't need the inner map. The outer one is already iterating over the objects in your array. You can also destructure the info object to url and name to make it a bit cleaner. Like this:

{NEXT_JS_COOL_SITES?.map(({ url, name }, index) => 
   <ListItem key={index}>
     <a href={url}>
       <Typography>{name}</Typography>
     </a>
   </ListItem> 
)}

But using index as key is not ideal. I'd recommend using a unique value that won't depend on the order. You could use url in this case.

CodePudding user response:

Can you share a screenshot of what you and and what the problem is ? from what I see index will take either the value "url" or "name"and will not describe an index.

remember that array.map takes these callback arguments in this order: value, index and the full array its referencing

  • Related