DEV Community

MOHSIN ALI SOOMRO
MOHSIN ALI SOOMRO

Posted on

loop throw dynamic key in array javascript

Problem

const example = [
  {
    "2021-10-11": [
      {
        id: 31,
        availableslots: 41,
        bookings_count: 0,
        start_time: "2021-10-11T06:00:00",
        finish_time: "2021-10-11T09:00:00",
        AM_PM: "AM",
        workingslot: 16,
        price: 15,
        postcode: "e18 8,e14 4",
        job_id: "9",
        base_price: 15
      },
      {
        id: 32,
        availableslots: 96,
        bookings_count: 2,
        start_time: "2021-10-11T06:00:00",
        finish_time: "2021-10-11T09:00:00",
        AM_PM: "PM",
        workingslot: 16,
        price: 15,
        postcode: "e18 8,e14 4",
        job_id: "9",
        base_price: 15
      }
    ],
    "2021-10-12": [
      {
        id: 31,
        availableslots: 41,
        bookings_count: 0,
        start_time: "2021-10-11T06:00:00",
        finish_time: "2021-10-11T09:00:00",
        AM_PM: "AM",
        workingslot: 16,
        price: 15,
        postcode: "e18 8,e14 4",
        job_id: "9",
        base_price: 15
      },
      {
        id: 32,
        availableslots: 96,
        bookings_count: 2,
        start_time: "2021-10-11T06:00:00",
        finish_time: "2021-10-11T09:00:00",
        AM_PM: "PM",
        workingslot: 16,
        price: 15,
        postcode: "e18 8,e14 4",
        job_id: "9",
        base_price: 15
      }
    ],
  }
];
Enter fullscreen mode Exit fullscreen mode

solution

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {example.map((d, i) => {
        var keys = Object.keys(d);
        return (
          <div>
              {d[keys[i]].map((i) => (
                <div>
                  <p>{i.id}</p>
                  <p>{i.start_time}</p>
                  <p>{i.finish_time}</p>
                </div>
              ))}
          </div>
        );
      })}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

codesandbox

Discussion (0)