gpt4 book ai didi

Javascript深层嵌套数组过滤器

转载 作者:行者123 更新时间:2023-12-03 00:04:51 27 4
gpt4 key购买 nike

我想使用 javascript 过滤器功能来过滤一些信息,但我似乎无法让它工作。鉴于我有一些原始数据如下:

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

我想按汽车名称在用户界面中过滤此数据。如果用户选择一个过滤器选项,该选项将返回带有 ['Audi'] 的数组。

我需要做什么才能得到以下响应:

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

我最好的猜测方法是:

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)

它似乎只是忽略了最后的过滤器:\如果有人对此有解决办法,我真的很感激帮助,对于精通 Javascript 方式的人来说,这可能相当简单。

最佳答案

当您期望的响应与原始原始数据类型不同时,您需要更多运算符。

在你的例子中,我使用 .map 函数来做到这一点:

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

const CAR_BRANDS = ["Audi", "Porsche"];

salesWeeks = salesWeeks
.filter(week => {
return week.locations
.some(location => {
return !!location
.cars.filter(car => CAR_BRANDS.includes(car.name)).length // return a bolean value length = 0 => false...
})
})
.map(week => {
week.locations = week.locations.map(l => {
l.cars = l.cars.filter(car => CAR_BRANDS.includes(car.name)); // only keep a car
return l;
});
return week;
});

console.log(JSON.stringify(salesWeeks, null, 4));

关于Javascript深层嵌套数组过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55006923/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com