I have two arrays, I need to filter this based on name.
const arr1 = ["Saab", "Volvo", "BMW", "Car3", "Car2", "Van", "Bus"];
const arr2 = [
{
name: "Saab",
url: "saab/"
},
{
name: "Volvo",
url: "volvo/",
children:[
{
name: "Van",
url: "van/"
},
{
name: "Bus",
url: "bus/"
},
]
},
{
name: "BMW",
url: "bmw/"
},
{
name: "SUV",
url: "suv/",
children:[
{
name: "Car1",
url: "car1/"
},
{
name: "Car2",
url: "car2/"
},
{
name: "Car3",
url: "car3/"
},
]
}
]
I tried with this code.
const result = arr2.filter((item) => arr1.includes(item.name);
This code working fine but it does not check children object in arr2, I need to check based on the arr1 values and if I have children object I need to check that name also. For example: name SUV is in the arr1 but car1 and car2 value are not in arr1 that time I need to remove that SUV object.
My output should be:
[
{
name: "Saab",
url: "saab/"
},
{
name: "Volvo",
url: "volvo/",
children:[
{
name: "Van",
url: "van/"
},
{
name: "Bus",
url: "bus/"
},
]
},
{
name: "BMW",
url: "bmw/"
},
]
How can I do this using javascript, is it possible to do in es6?