Антое
Антое

Reputation: 1

Js. Map inside map

In console I see key. But in browser I don’t see key, only element.title. Want to see in the browser:

key 1
title 1
title 2

key 2
title 3
title 4

{Object.entries(bob).map(([key, value]) => {
        return (
          console.log("key", key),
          (<Typography>{key}</Typography>),
          value.map((element) => (
            <Typography key={element.id}>{element.title}</Typography>
          ))
        )
      })}

Upvotes: 0

Views: 74

Answers (1)

Devorein
Devorein

Reputation: 1319

I'm assuming bob looks something like this

const bob = {
  1: [{title: 1}, {title: 2}],
  2: [{title: 3}, {title: 4}]
}

You can try out the following snippet

{Object.entries(bob).map(([key, value]) => {
  console.log("key", key);
  return (
    <>
      <Typography>{key}</Typography>
      {value.map((element) => (
        <Typography key={element.id}>{element.title}</Typography>
      ))}
    </>
  )
})}

Notice the <></> surrounding the key and the value, its called React Fragments. Since you can't return more than one react node, you need to either surround the return with a valid HTML element/React component or use a fragment

Upvotes: 1

Related Questions