I want to filter some information using the javascript filter functionality but i can't seem to get it to work. Given i have some raw data as below:
{
"salesWeeks": [
{
"date": "29/03/2019",
"locations": [
{
"name": "London",
"totalUnits": 15,
"cars": [
{
"name" : "Audi",
"units": 5
},
{
"name": "BMW",
"units": 10
}
]
}
]
},
{
"date": "29/03/2019",
"locations": [
{
"name": "Paris",
"totalUnits": 22,
"cars": [
{
"name" : "Audi",
"units": 2
},
{
"name": "BMW",
"units": 10
},
{
"name": "Porsche",
"units": 10
}
]
}
]
}
]
}
I want to filter this data in my UI by the name of the car. If a user selects a filter option which returns an array with ['Audi'].
What would i need to do in order to get the following response:
{
"salesWeeks": [
{
"date": "29/03/2019",
"locations": [
{
"name": "London",
"totalUnits": 15,
"cars": [
{
"name" : "Audi",
"units": 5
}
]
}
]
},
{
"date": "29/03/2019",
"locations": [
{
"name": "Paris",
"totalUnits": 22,
"cars": [
{
"name" : "Audi",
"units": 2
}
]
}
]
}
]
}
My best guess approach has been:
https://jsfiddle.net/hwt3k2sn/7/
var salesWeeks = [{"date":"29/03/2019","locations":[{"name":"London","totalUnits":15,"cars":[{"name":"Audi","units":5},{"name":"BMW","units":10}]}]},{"date":"29/03/2019","locations":[{"name":"Paris","totalUnits":22,"cars":[{"name":"Audi","units":2},{"name":"BMW","units":10},{"name":"Porsche","units":10}]}]}]
salesWeeks = salesWeeks
.filter(week => {
return week.locations
.some(location => {
return location
.cars.filter(cars => { cars.name == "Audi" })
})
})
console.log(salesWeeks)
it just seems to ignore the filter at the end though :\ if anyone has a fix for this i would really appreciate the help, it's probably fairly simple for someone well versed in the ways of the Javascript.
return location .cars.filter(cars => { cars.name == "Audi" }).length