Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...