Yaniv Suriyano
Yaniv Suriyano

Reputation: 77

Map inside map value

I tried show for each item in data array only the name key I need to show it with table.

const data = [{id: "111", name: "Danny", city: "NYC"},
              {id: "222", name: "Roni", city: "LDN}, 
              {id: "333", name: "Suzi", city: "TLV",
              {id: "444", name: "John", city: "SF"}
             ]
const config = [{fieldToShow: "name"}]


  <tbody>
  {data.map((row) => {
    return (
      <tr>
        {config.map((value) => {
          return <td>{row[value.field]}</td>;
        })}
      </tr>
    );
  })}

but it not work ...

Upvotes: 0

Views: 204

Answers (2)

Jamal
Jamal

Reputation: 848

you can do like this:

export default function Test() {
  const data = [
    { id: '111', name: 'Danny', city: 'NYC' },
    { id: '222', name: 'Roni', city: 'LDN' },
    { id: '333', name: 'Suzi', city: 'TLV' },
    { id: '444', name: 'John', city: 'SF' },
  ];
  const config = [{ fieldToShow: 'name' }];

  return (
    <tbody>
      {data.map((row) => (
        <tr>
          {data.map((row) => (
            <tr>
              {config.map((value) => (
                <td>{row[value.fieldToShow]}</td>
              ))}
            </tr>
          ))}
        </tr>
      ))}
    </tbody>
  );
}

Upvotes: 1

Ivo
Ivo

Reputation: 2510

Your config object has a key fieldToShow :

const config = [{fieldToShow: "name"}]

while you are trying to get the key field in your map. You change this line:

  return <td>{row[value.field]}</td>;

to this:

  return <td>{row[value.fieldToShow]}</td>;

Upvotes: 2

Related Questions