如何从数组内部的对象中找到匹配的键/对值

我正在使用Gatsby在无头的Shopify商店工作,在构建强大的产品选择器时遇到了一些麻烦。

I have an options object that looks like this:

{
  extras: "Pouch only",
}

每个产品的键和值都不同,所以我不知道这些值。

I have a variants array that will have a key/value pair that matches this object. Here is the shape of the variants array:

[
  {
    extras: "Pouch only",
    ...otherValues,
  },
  {
    extras: "Add tassel",
    ...otherValues,
  },
  {
    extras: "Add charm",
    ...otherValues,
  },
  {
    extras: "Add tassel & charm",
    ...otherValues,
  },
  {
    sizes: "S",
    ...otherValues,
  },
  {
    sizes: "M",
    ...otherValues,
  },
  {
    sizes: "L",
    ...otherValues,
  },
  {
    sizes: "XL",
    ...otherValues,
  },
];

如果我提前知道变体的名称,则可以执行以下操作:

const newVariant = variants.find((v) => {
  return v.extras === options.extras;
});

在不知道密钥名称的情况下如何做同样的事情?

评论
  • 贪婪的想念
    贪婪的想念 回复

    Take the entries of the option object and stringify them. Then, when searching through the variants, find (or filter) by the ones which have an entry matching the entry previously stringified:

    const optionsEntryVariants = Object.entries(options).map(JSON.stringify);
    const matchingVariants = variants.filter(
      variant => Object.entries(variant).some(
        entry => optionsEntryVariants.includes(JSON.stringify(entry))
      )
    );
    
    const options = {
      extras: "Pouch only",
    };
    
    const optionsEntryVariants = Object.entries(options).map(JSON.stringify);
    
    const variants = [
      {
        extras: "Pouch only",
        someOtherProp: 'someOtherVal',
      },
      {
        extras: "Add tassel",
        someOtherProp: 'someOtherVal',
      },
      {
        extras: "Add charm",
        someOtherProp: 'someOtherVal',
      },
      {
        extras: "Add tassel & charm",
        someOtherProp: 'someOtherVal',
      },
      {
        sizes: "S",
        someOtherProp: 'someOtherVal',
      },
      {
        sizes: "M",
        someOtherProp: 'someOtherVal',
      },
      {
        sizes: "L",
        someOtherProp: 'someOtherVal',
      },
      {
        sizes: "XL",
        someOtherProp: 'someOtherVal',
      },
    ];
    
    const matchingVariants = variants.filter(
      variant => Object.entries(variant).some(
        entry => optionsEntryVariants.includes(JSON.stringify(entry))
      )
    );
    
    console.log(matchingVariants);
  • 萌嘟嘟
    萌嘟嘟 回复

    Using Object.entries you can retrieve key/value pairs of the object, and check if .some(or .every depending on your needs) match:

    const newVariant = variants.find((v) => Object.entries(options).some(([key, value]) => v[key] === value));