如何在javascript中基于多个选项过滤嵌套数据?
我有JSON数据,其结构如下:如何在javascript中基于多个选项过滤嵌套数据?,javascript,Javascript,我有JSON数据,其结构如下: data = [ { "id": 100, "floorplans": [ { "bhk": 1, ...some other fields }, { "bhk": 3, ...some other fields }, { "bhk": 2,
data = [
{
"id": 100,
"floorplans": [
{
"bhk": 1,
...some other fields
},
{
"bhk": 3,
...some other fields
},
{
"bhk": 2,
...some other fields
}
]
},
{
"id": 200,
"floorplans": [
{
"bhk": 1.5,
...some other fields
},
{
"bhk": 1,
...some other fields
},
{
"bhk": 2.5,
...some other fields
}
]
},
{
"id": 300,
"floorplans": [
{
"bhk": 1,
...some other fields
},
{
"bhk": 4,
...some other fields
},
{
"bhk": 2,
...some other fields
}
]
}]
现在我有了另一个数组,比如tempArray=[2,3],现在我只想从bhk==2的数据数组中过滤那些对象,即tempArray[0]或bhk==3,即tempArray[1]
我无法理解如何过滤这些数据?下面的代码不起作用,我找不到这种过滤的任何例子
代码:
现在由于tempArray有2和3个元素,所以我只想显示数据[0]和数据[2]对象,而不是数据[1],因为数据[1]既不包含2也不包含3。您可以简单地使用with并过滤掉temp array中存在bhk
的数据
请尝试以下操作:
let data=[{“id”:100,“平面布置图”:[{“bhk”:1},{“bhk”:3},{“bhk”:2}},{“id”:200,“平面布置图”:[{“bhk”:1.5},{“bhk”:1},{“bhk”:2.5},{“id”:300,“平面布置图”:[{“bhk”:1},{“bhk”:4},{“bhk”:2}];
设temp=[2,3];
让filterData=data.filter(a=>a.floorplan.some(e=>temp.includes(e.bhk));
console.log(filterData)代码>
var filtered_data = data.filter((val) => {
return val.floorplans.indexOf(tempArray[0]) !== -1;
})