Home > front end >  Get data from Array of objects within an array
Get data from Array of objects within an array

Time:09-11

how do I map over the following array of arrays and show each data contained in the objects separately? i.e I want the objects on the first array to be shown when a row on a table is expanded, the ones in the second array should be shown when another row is expanded and so on.

enter image description here

CodePudding user response:

try to map like this:

    array.map(subarray => 
     subarray.map(item => ({ name: item.name, quantity: item.quantity })));

CodePudding user response:

Why not loop over them and depict it as collapses?

import { useState } from "react";

const Collapse = ({ data, index }) => {
  const [isOpen, setOpen] = useState(false);

  const children = data.map(({ name, quantity }, key) => {
    return (
      <div key={key}>
        <span>{`${name}:`}</span>
        <span>{quantity}</span>
      </div>
    );
  });

  return (
    <div>
      <button onClick={() => setOpen(!isOpen)}>{`List ${index}`}</button>
      <div>{isOpen && children}</div>
    </div>
  );
};

export default function App() {
  const data = [
    [
      { name: "Tusker", quantity: 9 },
      { name: "Guiness", quantity: 9 }
    ],
    [
      { name: "Choma", quantity: 9 },
      { name: "Sprite", quantity: 9 }
    ]
  ];

  return (
    <div>
      {data.map((localList, index) => {
        return <Collapse key={index} data={localList} index={index} />;
      })}
    </div>
  );
}

You might also check, if the collapse should be displayed at all - there might not always be data available.

This example isn't styled at all but it should lead you into the right direction.

  • Related