0

I have a nested JSON which I am trying to render it into a table. The idea is to populate by iterating through the JSON. My issue is when I am Iterating through Tags and trying to populate in the environment Column. It works fine if the key exists, but if the key doesn't exist it shifts TD's to previous columns.

For example, below in the image, you can see in the first row that web to ENV column, instead of Purpose column. for the other two, the table renders fine since the key exists.

Table

import React, { Component } from "react";
import { Table } from "reactstrap";
class Example extends Component {
  state = {
    data: [
      {
        id: "1",
        States: "many",
        Purpose: "web",
        Tags: [
          {
            Key: "Name",
            Value: "server1"
          }
        ]
      },
      {
        id: "2",
        States: "Single",
        Purpose: "App",
        Tags: [
          {
            Key: "Name",
            Value: "server2"
          },
          {
            Key: "env",
            Value: "qa"
          }
        ]
      },
      {
        id: "3",
        States: "None",
        Purpose: "DB",
        Tags: [
          {
            Key: "env",
            Value: "qa"
          },
          {
            Key: "Name",
            Value: "server3"
          }
        ]
      }
    ]
  };
  render() {
    let envs;
    return (
      <Table className="align-items-center table-flush" responsive>
        <thead className="thead-light">
          <tr>
            <th scope="col">ID</th>
            <th scope="col">States</th>
            <th scope="col">Env</th>
            <th scope="col">Purpose</th>
          </tr>
        </thead>
        <tbody>
          {this.state.data.map(info => (
            <tr>
              <th scope="row">{info.id}</th>
              <td>{info.States}</td>
              {info.Tags.filter(env => env.Key === "env").map(e => (
                <td>{e.Value}</td>
              ))}
              <td>{info.Purpose}</td>
            </tr>
          ))}
        </tbody>
      </Table>
    );
  }
}

export default Example;

1 Answer 1

1

Inside your render method, you can do:

<td>{info.Tags.filter(env => env.Key === "env").map(e => e.Value).join(' ')}</td>

So instead of wrapping the returned value from the map in td, you have to wrap the entire thing in the tags.

Sign up to request clarification or add additional context in comments.

1 Comment

this works like a charm, thank you so much. I spent a lot of hours on this trying to figure out. finally, it works. thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.