【问题标题】:Filters nested arrays to find unique product collections过滤嵌套数组以查找独特的产品集合
【发布时间】:2021-01-29 06:39:15
【问题描述】:

我正在使用 Next.js 和 Shopify 构建一个网站。我需要创建一个页面,列出与某个 productType 匹配的所有集合。

我能够找到从 GraphQL API 获取此数据的唯一方法是搜索所有产品,按 productType 过滤并尝试从该列表中查找所有唯一集合。

Here is an example of what that looks like.

我怎样才能只获得独特的收藏? 我试过了,不幸的是它不起作用:

const collections = [
  ...new Set([
    ...allCollectionsByType.filter(({ node }) => {
      const collection = node.collections.edges;
      return collection[0]?.node;
    }),
  ]),
];

对不起,如果这是一个简单的问题,我真的不擅长使用嵌套数组!

感谢任何帮助????

【问题讨论】:

  • 你应该重现:(你自己)制作一个代表 allCollectionsByType 的小 json,应用你的 5 行,然后检查结果。如果您仍然无法找到解决方案,请在此处更新您的最小复制示例?

标签: javascript reactjs next.js shopify


【解决方案1】:

我设法让它工作。我意识到 Set 无法确定其中的对象不是唯一的,所以我必须先对它们进行字符串化。

我不认为这是最好的实现(我在数组中循环了几次),但它确实有效。

这是我的解决方案:

  const collections = allCollectionsByType.map(({ node }) => {
    const collection = node.collections.edges?.[0]?.node;
    return JSON.stringify(collection);
  });

  const unique = Array.from(new Set(collections))
    .filter((node) => typeof node === 'string')
    .map((node: string) => JSON.parse(node));

【讨论】:

    猜你喜欢
    • 2018-04-08
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    相关资源
    最近更新 更多