'Filtering array from object nested in array react

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



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

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?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sanjeev_gupta2812
Solution 2 Ilyes42
Solution 3