Home > Software engineering >  Filtering array from object nested in array react
Filtering array from object nested in array react

Time:04-01

I have an array of object which objects have array, and my problem is to filter objects based on values from a nested array.

     const skus = [
         {
id: 1,features: ["Slim"],
         fields: [
              { label: "Material", value: "Material1" },
            ]
          },
          {
            id: 2,
            features: ["Cotton"],
            fields: [
              { label: "Material", value: "Material2" },
            ]
          },
          {
            id: 3,
            features: ["Slim"],
            fields: [
              { label: "Material", value: "Material3" },
            ]
          }
        ];
    

output should be array based on features array, example:

 const result = [{
            id: 2,
            features: ["Cotton"],
            fields: [
              { label: "Material", value: "Material2" },
              { label: "Type", value: "Type2" }
            ]
          }]

I tried to using filter method, but it only works on on objects, but not on arrays nested in objects

CodePudding user response:

Well to understand better you must understand that Array is also a special object only in javascript so you can perform filter on objects or the nested objects too.

skus.filter((item,keys)=>{
    return item['features'].includes("Cotton") // Pass the search term in includes
})

With this you can achieve your goal. Let me know if this works for you.

CodePudding user response:

I got the same output of the example you gave using :

skus.filter(sku => sku.features.includes("Cotton"));

I hope you can explain a bit more.

CodePudding user response:

The Filter method allows you to delve deeper into an objects properties and perform comparisons.

    const skus = [
                    { id: 1, features: ["Slim"], fields: [{ label: "Material", value: "Material1" },] },
                    { id: 2, features: ["Cotton"], fields: [{ label: "Material", value: "Material2" },] },
                    { id: 3, features: ["Slim"], fields: [{ label: "Material", value: "Material3" },] }
                ];
    
    let featureName = "Cotton"
    let results = skus.filter(s => s.features.includes(featureName))
    console.log(results);

I'm unsure where "{ label: "Type", value: "Type2" }" suddenly comes from in your results though?

  • Related