Next.js Discord

Discord Forum

converting an object to jsx

Answered
Japanese jack mackerel posted this in #help-forum
Open in Discord
Japanese jack mackerelOP
i have an object of data that im iterating over to create some jsx but its currently not working as intended
let test2 = [];
  for (const [category, options] of Object.entries(categoryOptions)) {
    test2 += `${<div key={category} >
      <h2 className={styles.category_name}>{category}</h2>
      <hr />
      <div className={styles.category}>
        {options.map(resource => (
          <Sidebar_Checkbox key={resource} resource={resource} />
        ))}
      </div>
    </div>}`
  }

  let test = Object.values(categoryOptions).map(category => {
    console.log(category);
    <div key={category} >
      <h2 className={styles.category_name}>{category}</h2>
      <hr />
      <div className={styles.category}>
        {category.map(resource => (
          <Sidebar_Checkbox key={resource} resource={resource} />
        ))}
      </div>
    </div>
  }
  )
  console.log("Hello: " + test2)
  return (
    <div >
      {
        test
      }
    </div>
  )

the logic works but for the first one all that gets displayed on the website is "[object Object][object Object][object Object][object Object][object Object]" and the second one nothing gets displayed
Answered by Ray
I think you didn't return it in here?
  let test = Object.values(categoryOptions).map(category => {
    console.log(category);
    return (
      <div key={category} >
        <h2 className={styles.category_name}>{category}</h2>
        <hr />
        <div className={styles.category}>
          {category.map(resource => (
            <Sidebar_Checkbox key={resource} resource={resource} />
          ))}
        </div>
      </div>
    )
  }
View full answer

6 Replies

Answer
@Japanese jack mackerel ok that fixed the invis but now its skipping the category name. i think Object.values just returns the subarrays and not the keys as well
try this
let test = Object.entries(categoryOptions).map(([category, options]) => {
    console.log(category);
    return (
      <div key={category} >
        <h2 className={styles.category_name}>{category}</h2>
        <hr />
        <div className={styles.category}>
          {options.map(resource => (
            <Sidebar_Checkbox key={resource} resource={resource} />
          ))}
        </div>
      </div>
    )
  }
btw, I don't know how categoryOptions look like. I guess it is what you were trying to do 😆
@Ray btw, I don't know how categoryOptions look like. I guess it is what you were trying to do 😆
Japanese jack mackerelOP
tyyyy that fixed it, part of the error was in how sidebar_checkbox was handling the resource variable