У меня есть многомерный объект с несколькими слоями вложенных массивов, и я пытаюсь отобразить все из них в одной go, но не знаю, как - PullRequest
1 голос
/ 30 апреля 2020

У меня есть сложный объект, с которым я работаю, чтобы создать таблицу контактных данных, но у меня возникают проблемы с вложенными массивами.

Я пытался использовать вложенные циклы и недавно переместился к вложенному подходу .map () , но я все еще бью стену, где я не могу получить доступ к двум последним массивам объектов (номера телефонов и адреса), чтобы распечатать их, и я полностью раскручиваю свои колеса.

Я работаю над этим более дня, и я совершенно ошеломлен, как подойти к этому.

Edit crazy-edison-6l6ue

Ожидаемый результат:

Name | Member | Telephone | Email | Addresses

Ben B| Friend | 610-535-1234 | ben@gmail.com | 123 Fiction Drive,Denver
                215-674-6789                   234 Dreary Ln,Seattle 

Alice | Family| 267-333-1234 | ally@aim.com  | 437 Chance St, Pitts.

Компонент:

  const rows = contacts.contactGroups.map(group =>
    <>
    <thead>
        <tr>
          <td>Name</td>
          <td>Member Type</td>
          <td>Telephone</td>
          <td>Email</td>
          <td>Address</td>
        </tr>
      </thead> 
  <tbody>
    <tr>{group.contactGroup}</tr>
    <td>
    <tr>
      {group.contacts.map(contact => <td>
      {contact.fullName}</td>)}
      {group.contacts.map(contact => <td>
      {contact.member}</td>)}
      {/* {group.contacts.map(contact => <td>  
     </td>)}
      {group.contacts.map(contact => 
      <td>{contact.addresses} 
      </td>)}  */}
    </tr>
    </td>
  </tbody>
  </>);

Структура данных:

export default {
  count: 1,
  contactGroups: [
    {
      contactGroup: "Family",
      count: 1,
      contacts: [
        {
          member: "Uncle",
          fullName: "BENJAMIN BILLIARDS",
          lastName: "BILLIARDS",
          firstName: "BENJAMIN",
          email: "shark@billiards.com",
          phoneNumbers: [
            {
              telephoneNumber: "123-456-7899",
              type: "mobile"
            },
            {
              telephoneNumber: "610-555-7625",
              type: "work"
            }
          ],
          addresses: [
            {
              addressLine1: "123 FAMILY ST",
              addressLine2: "APT 1208",
              city: "ATLANTA",
              state: "GEORGIA",
              zipCode: "12345"
            },
            {
              addressLine1: "456 WORKING BLVD",
              addressLine2: "",
              city: "ATLANTA",
              state: "GEORGIA",
              zipCode: "12345"
            }
          ]
        }
      ]
    },
    {
      contactGroup: "Friends",
      count: 1,
      contacts: [
        {
          member: "School Friend",
          fullName: "HANS ZIMMER",
          lastName: "ZIMMER",
          firstName: "HANS",
          email: "hans@pirates.com",
          phoneNumbers: [
            {
              telephoneNumber: "267-455-1234",
              type: "mobile"
            }
          ],
          addresses: [
            {
              addressLine1: "789 FRIEND ST",
              addressLine2: "",
              city: "SAN DIEGO",
              state: "CALIFORNIA",
              zipCode: "67890"
            },
            {
              addressLine1: "234 CANARY ST",
              addressLine2: "",
              city: "SEATTLE",
              state: "WASHINGTON",
              zipCode: "67890"
            }
          ]
        }
      ]
    }
  ]
};

Ответы [ 2 ]

1 голос
/ 30 апреля 2020

Вы можете просто использовать forEach, который, я думаю, будет гораздо проще понять следующим образом:

https://codesandbox.io/s/clever-euclid-1bdl5

export const ContactsGrid = (props: Props) => {
  const { contacts } = props;

  const rows = [];

  contacts.contactGroups.forEach(contactGroup => {
    //First row for group name
    const groupRow = (
      <tr>
        <td>{contactGroup.contactGroup}</td>
      </tr>
    );

    // Data for that group
    const contactRows = [];
    contactGroup.contacts.forEach(contact => {
      const row = (
        <tr>
          <td>{contact.fullName}</td>
          <td>{contact.member}</td>
          <td>
            {contact.phoneNumbers.map(number => (
              <div>
                {number.type} : {number.telephoneNumber}
              </div>
            ))}
          </td>
          <td>{contact.email}</td>
          <td>
            {contact.addresses.map(add => (
              <div>
                {add.addressLine1}
                <br /> {add.addressLine2} <br /> {add.city}, {add.state}
                <br />
                {add.zipCode}
              </div>
            ))}
          </td>
        </tr>
      );
      contactRows.push(row);
    });

    // Add the group row and all the data rows to final rows arr to be rendered
    rows.push(groupRow, ...contactRows);
  });

  return (
    <table>
      <thead>
        <tr>
          <td>Name</td>
          <td>Member Type</td>
          <td>Telephone</td>
          <td>Email</td>
          <td>Address</td>
        </tr>
      </thead>
      <tbody>{rows}</tbody>
    </table>
  );
};

Надеюсь, это поможет !

0 голосов
/ 30 апреля 2020

Другой подход, согласно вашей ожидаемой выходной таблице

https://codesandbox.io/s/suspicious-leaf-ozwu1?fontsize=14&hidenavigation=1&theme=dark

interface Row {
  name: string;
  memberOf: string;
  memberType: string;
  telephones: Array<PhoneNumber>;
  email: string;
  addresses: Array<Address>;
}

export const ContactsGrid = (props: Props) => {
  const { contacts } = props;

  let rows: Array<Row> = [];
  contacts.contactGroups.forEach(contactG => {
    contactG.contacts.forEach(contact => {
      rows.push({
        name: contact.fullName,
        memberOf: contactG.contactGroup,
        memberType: contact.member,
        telephones: contact.phoneNumbers,
        email: contact.email,
        addresses: contact.addresses
      });
    });
  });

  return (
    <table>
      <thead>
        <tr>
          <td>Name</td>
          <td>Member Type</td>
          <td>Telephone</td>
          <td>Email</td>
          <td>Address</td>
        </tr>
      </thead>
      <tbody>
        {rows.map(row => {
          return (
            <tr>
              <td>{row.name}</td>
              <td>{row.memberType + " (" + row.memberOf + ")"}</td>
              <td>
                {row.telephones.map(phone => {
                  return <p>{phone.telephoneNumber}</p>;
                })}
              </td>
              <td>{row.email}</td>
              <td>
                {row.addresses.map(address => {
                  return <p>{address.addressLine1 + ", " + address.city}</p>;
                })}
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...