Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

javascript - Filters nested arrays to find unique product collections

I'm building a site with Next.js and Shopify. I need to create a page that will list all the collections that match a certain productType.

The only way I've been able to find to get this data from the GraphQL API is to search for all products, filtered by productType and try to find all the unique collections from that list.

Here is an example of what that looks like.

How can I get just the unique collections? I tried this unfortunately it doesn't work:

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

Sorry if this is an easy question, I'm really bad at working with nested arrays!

Appreciate any help ??

question from:https://stackoverflow.com/questions/65949884/filters-nested-arrays-to-find-unique-product-collections

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I managed to get it working. I realised that the Set couldn't work out that the objects in it were not unique, so I had to stringify them first.

I don't think this is the best implementation (I'm looping through the array several times) but it does work.

Here is my solution to get this to work:

  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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...