如果对象包含值存在于另一个数组中的属性,则过滤对象数组

bei*_*ogi 4 javascript arrays javascript-objects

我有以下对象数组。

const abc = [
      {
        sku: 1,
        features: ["Slim"],
        fields: [
          { label: "Material", value: "Material1" },
          { label: "Type", value: "Type1" },
        ]
      },
      {
        sku: 2,
        features: ["Cotton"],
        fields: [
          { label: "Material", value: "Material2" },
          { label: "Type", value: "Type1" },
        ]
      },
      {
        sku: 3,
        features: ["Cotton"],
        fields: [
          { label: "Material", value: "Material3" },
          { label: "Type", value: "Type2" },
        ]
      }
    ];
Run Code Online (Sandbox Code Playgroud)

我只想过滤那些特征和字段值存在于这个中的对象

const fieldsArr = ["Material1", "Material2", "Type1", "Slim"]
Run Code Online (Sandbox Code Playgroud)

预期输出为

let output = [
      {
        sku: 1,
        features: ["Slim"],
        fields: [
          { label: "Material", value: "Material1" },
          { label: "Type", value: "Type1" },
        ]
      },
      {
        sku: 2,
        features: ["Cotton"],
        fields: [
          { label: "Material", value: "Material2" },
          { label: "Type", value: "Type1" },
        ]
      },
    ]
Run Code Online (Sandbox Code Playgroud)

我解决了这样的功能部分

abc.forEach(e => {
      if (e.features.some(v => fieldsArr.indexOf(v) !== -1)) {
        output.push(e);
      }
    });
Run Code Online (Sandbox Code Playgroud)

但是我在过滤字段部分时遇到了问题。有没有办法以优化的方式根据上述条件过滤对象。

Nin*_*olz 6

您还需要迭代嵌套数组。

const
    abc = [{ sku: 1, features: ["Slim"], fields: [{ label: "Material", value: "Material1" }, { label: "Type", value: "Type1" }] }, { sku: 2, features: ["Cotton"], fields: [{ label: "Material", value: "Material2" }, { label: "Type", value: "Type1" }] }, { sku: 3, features: ["Cotton"], fields: [{ label: "Material", value: "Material3" }, { label: "Type", value: "Type2" }] }],        fieldsArr = ["Material1", "Material2", "Type1", "Slim"],
    result = abc.filter(({ features, fields }) =>
        features.some(v => fieldsArr.includes(v)) ||
        fields.some(({ value }) => fieldsArr.includes(value))
    );

console.log(result);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)