Home > Enterprise >  How to render two arrays in jsx
How to render two arrays in jsx

Time:09-14

So I have two lists: categories and channels both of them have two objects. Now I want to loop through each of them but the problem is no matter how I loop through them I always end up with two results either the items are displayed 4 times (should be 2) or the nested loop (channel loop) is displaying all of its items on all the categories.

     <div className="fixed inset-0 m-auto bg-[#2F3136]">
        <div>
          <h1>{server?.title}</h1>
          <ArrowDropDownOutlinedIcon />
        </div>

        {categories?.map((category) => (
          <div key={category._id}>
            <h1>{category.title}</h1>
            {channels?.map((channel) => (
              <h1>{channel.title}</h1>
            ))}
          </div>
        ))}
      </div>

CodePudding user response:

You mean to loop only channels in that caterogy? You should filter your channels before you loop them.

Lets say you each channel contains category prop which is equal to category

    <div className="fixed inset-0 m-auto bg-[#2F3136]">
        <div>
          <h1>{server?.title}</h1>
          <ArrowDropDownOutlinedIcon />
        </div>

        {categories?.map((category) => (
          <div key={category._id}>
            <h1>{category.title}</h1>
            {channels?.filter((channel)=>channel.category===category)
.map((channel) => (
              <h1>{channel.title}</h1>
            ))}
          </div>
        ))}
      </div>

CodePudding user response:

The thing is on each iteration of map, it is expecting some output to be returned that it can display on the screen, Now if there is a loop inside it you need to explicitly tell map to return what and what on the end of each iteration with return (). Here is the example (You need to wrap it inside an element like return () i mean or <></> etc): Make sure you are returning the second map itself and not just the final expected output:

        <tbody>
          {Object.keys(templates).map(function (template_name) {
            return (
              <tr key={template_name}>
                <tr>
                  <td>
                    <b>Template: {template_name}</b>
                  </td>
                </tr>
                {templates[template_name].items.map(function (item) {
                  return (
                    <tr key={item.id}>
                      <td>{item}</td>
                    </tr>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
  • Related