next.js 下一篇:JS - Map by value

nnvyjq4y  于 2023-08-04  发布在  其他
关注(0)|答案(2)|浏览(84)
{guideData?.night_out_list.length > 0 &&
  guideData?.night_out_list?
  .map((guide_data, i) => (

    // guide_data.main_category 
    
))}

字符串
我有一个类似上面的循环,它返回一组19个结果,如下所示:

{
    "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": ""
}


基本上有3个不同的main_category,分别是夜总会、酒吧和鸡尾酒以及其他。
我想做的是遍历每一个。所以首先它会循环夜总会,然后酒吧和鸡尾酒,然后所有的结果与其他。
我不知道我会怎么做,所以任何希望是非常赞赏!

wqnecbli

wqnecbli1#

如果我理解正确的话,你想根据main_category对结果进行分组,以便单独显示它们?在这种情况下,你可以使用下面的例子来让你继续:

"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
}

字符串
dataByMainCategory将包含一个由所有主要类别及其关联数据组成的对象。
这不一定是客户端组件,可以在服务器上完美运行,特别是如果您不希望数据在客户端运行时发生更改。

xyhw6mcr

xyhw6mcr2#

我得到了这个工作如下:

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>

字符串

相关问题