Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects if object contains attribute with value present in another array

I have the following array of 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" },
        ]
      }
    ];

I want to filter only those objects whose features and fields value are present in this

const fieldsArr = ["Material1", "Material2", "Type1", "Slim"]

Expected Output is

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" },
        ]
      },
    ]

I solved the features part like this

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

But I'm having problem with filtering the fields part. Is there a way to filter the objects based on the above condition in an optimized way.

like image 435
beingyogi Avatar asked Jan 25 '23 06:01

beingyogi


1 Answers

You need to iterate the nested arrays as well.

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);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 197
Nina Scholz Avatar answered Jan 27 '23 18:01

Nina Scholz