0
{guideData?.night_out_list.length > 0 &&
  guideData?.night_out_list?
  .map((guide_data, i) => (

    // guide_data.main_category 
    
))}

I have a loop like the above which returns a set of 19 results like so:

{
    "main_category": "Nightclubs",
    "type_title": "Nightclub",
    "location_name": "Fig 19",
    "location_link": "",
    "location_photo": false,
    "location_description": ""
}

{
    "main_category": "Bars & Cocktails",
    "type_title": "Cocktail Bar",
    "location_name": "Mother's Ruin",
    "location_link": "",
    "location_photo": false,
    "location_description": ""
}

There are essentially 3 different main_category which are Nightclubs, Bars & Cocktails and Other.

What I want to do is loop through each one of these. So firstly it would loop Nightclubs, then Bars & Cocktails and then all the results with Other.

I'm not sure how I would do this so any hope is much appreciated!

nsilva
  • 5,184
  • 16
  • 66
  • 108
  • 1
    Does this answer your question? [Grouping JSON by values](https://stackoverflow.com/questions/38575721/grouping-json-by-values) – Emre Jul 31 '23 at 10:21

2 Answers2

0

If I understood correctly, you want to group your results based on their main_category to display them separately? In that case you can use the following example to get you going:

"use client";

import { useMemo } from "react";

export default MyComponent(props) {
  const { data = [] } = props;

  const categories = useMemo(() => {
    const results = data.map(entry => entry.main_category);
    return [...new Set(data)]; // using the set constructor removes duplicates
  }, [data]);

  // returns { someCategory: [], otherCategory: [] }
  const dataByMainCategory = useMemo(() => {
    const map = {};    
    for (const category of categories) {
      map[category] = data.filter(entry => entry.main_category === category);
    }
    return map;
  }, [data, categories])

  // rest of your code here
}

The dataByMainCategory will contain an object that consists of all the main categories and their associative data.


This does not necessarily be a client component and could be ran perfectly fine on the server, especially if you do not expect your data to change at client runtime.

Fabio Nettis
  • 1,150
  • 6
  • 18
0

I got this working as follows:

const nightOutData = guideData?.night_out_list;

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
var groupedByCat = groupBy(nightOutData, 'main_category')



<div>
  {Object.keys(groupedByCat).map((category,index) => {
    return (
      <div key={index}>
        <h2>{category}</h2>

        {groupedByCat[category].map((memb,i) => {
          return (
            <div key={i}>
              {memb.location_name}
            </div>
          );
        })}

        <hr />
      </div>
    );
  })}
</div>
nsilva
  • 5,184
  • 16
  • 66
  • 108