我有一个嵌套的数据数组。我可以根据自己的状况获得第一组数据,但是当我在此结果集上应用Array.filter
时,并没有给我预期的结果。
{
"data": [
{
"Date": "02/04/2019",
"Total": "1000",
"Success": "850",
"Failure": "150",
"FailureDeatils": [
{
"name": "Reason1",
"Count": 2,
"Description": [
{
"DescriptionID": "01",
"Status": "Failure Point1"
},
{
"DescriptionID": "01",
"Status": "Failure Point1"
}
]
},
{
"name": "Reason2",
"Count": 6,
"Description": [
{
"DescriptionID": "01",
"Status": "Failure Point1"
},
{
"DescriptionID": "01",
"Status": "Failure Point1"
}
]
}
]
},
{
"Date": "03/04/2019",
"Total": "800",
"Success": "750",
"Failure": "150",
"FailureDeatils": [
{
"name": "Reason1",
"Count": 3,
"Description": [
{
"DescriptionID": "01",
"Status": "Failure Point1"
},
{
"DescriptionID": "01",
"Status": "Failure Point1"
}
]
},
{
"name": "Reason2",
"Count": 1,
"Description": [
{
"DescriptionID": "01",
"Status": "Failure Point1"
},
{
"DescriptionID": "01",
"Status": "Failure Point1"
}
]
}
]
}
]
}
首先,我已应用以下Array.filter
来基于日期获取FailureDetails:
var filtered = data
.filter(value => value.Date == "02/04/2019")
.map(e => e.FailureDeatils);
这将导致以下输出:
FailureDeatils:[{"name":"Reason1","Count":2,"Description":[{"DescriptionID": "01","Status": "Failure Point1"},{"DescriptionID": "01","Status": "Failure Point1"}]},{"name":"Reason2","Count":6,"Description":[{"DescriptionID": "01","Status": "Failure Point1"},{"DescriptionID": "01","Status": "Failure Point1"}]}]
现在基于原因,即原因1或原因2,我想获取描述。但是,当我对此应用Array.filter
时,它将返回未定义的输出。
我要去哪里错了?
答案 0 :(得分:2)
您将在过滤后的数组上应用过滤器以获取结果,但是,由于它将是一个数组的数组,因此您也需要在过滤后的数组上进行映射。
但是,您可以简单地使用reducer来展平初始FailureDescription数组,而不是对其进行映射。
var data = [
{
"Date": "02/04/2019",
"Total": "1000",
"Success": "850",
"Failure": "150",
"FailureDeatils": [
{
"name": "Reason1",
"Count": 2,
"Description": [
{
"DescriptionID": "01",
"Status": "Failure Point1"
},
{
"DescriptionID": "01",
"Status": "Failure Point1"
}
]
},
{
"name": "Reason2",
"Count": 6,
"Description": [
{
"DescriptionID": "01",
"Status": "Failure Point1"
},
{
"DescriptionID": "01",
"Status": "Failure Point1"
}
]
}
]
},
{
"Date": "03/04/2019",
"Total": "800",
"Success": "750",
"Failure": "150",
"FailureDeatils": [
{
"name": "Reason1",
"Count": 3,
"Description": [
{
"DescriptionID": "01",
"Status": "Failure Point1"
},
{
"DescriptionID": "01",
"Status": "Failure Point1"
}
]
},
{
"name": "Reason2",
"Count": 1,
"Description": [
{
"DescriptionID": "01",
"Status": "Failure Point1"
},
{
"DescriptionID": "01",
"Status": "Failure Point1"
}
]
}
]
}
]
var filtered = data
.filter(value => value.Date == "02/04/2019")
.reduce((acc,e) => acc.concat(e.FailureDeatils), []);
const reason = "Reason1";
var res = filtered.filter((data) => data.name == reason).reduce((acc, item) =>{
acc = acc.concat(item.Description);
return acc;
}, []);
console.log(res);