[英]how to filter a complex object in react
I have an object like the following.我有一个 object,如下所示。
example:[
{
"Id":"100",
"value":"Egor1",
"children":{
"pilot":[
{
"Properties":{
"Id":123,
"History":[
20191101,
20191112,
20191103
]
}
}
]
}
},
{
"Id":"200",
"value":"Egor2",
"children":{
"pilot":[
{
"Properties":{
"Id":234,
"History":[
20191001,
20191012,
20191003,
20190902
]
}
}
]
}
},
{
"Id":"300",
"value":"Egor3",
"children":{
"pilot":[
{
"Properties":{
"Id":456,
"History":[
20190901,
20190912,
20190903,
20191101
]
}
}
]
}
}
] ]
I have an input 20191101. Sometimes input can be 20191101,20191001.我有一个输入 20191101。有时输入可以是 20191101,20191001。 I need to filter the example if
如果我需要过滤示例
children.pilot.properties.history[0]=== 20191101.
I tried the following:我尝试了以下方法:
const result = example.filter( task => task.children.pilot.properties.history.includes(getPbfValueByFilter(task.childen, input))
);
getPbfValueByFilter method: getPbfValueByFilter 方法:
const getPbfValueByFilter = (allChilden, input) => {
const { features } = allChilden.pilot;
const test = input.toString().split(',');
if (isUndefined(features) || isEmpty(features)
|| isUndefined(features.properties.History)) {
return [];
}
test.map((each) => {
if (each === features.properties.History[0]) {
console.log("here" + features.properties.History[0])
return allChilden;
}
});
};
expected output:预期 output:
[
{
"Id": "100",
"value": "Egor1",
"children": {
"pilot": [
{
"Properties": {
"Id": 123,
"History": [
20191101,
20191112,
20191103
]
}
}
]
}
}
]
I am getting the console part.我得到了控制台部分。 But it is unable to fetch the result.
但它无法获取结果。 I assume that 'includes' is not working as expected.
我认为“包含”没有按预期工作。 What went wrong.
什么地方出了错。 Please advice.
请指教。 TIA.
TIA。
You can make use of some
with filter
.您可以使用
some
与filter
。 Let me know if this is what you are looking for:让我知道这是否是您正在寻找的:
var input=[20191101]; var example=[{ "Id":"100", "value":"Egor1", "children":{ "pilot":[ { "Properties":{ "Id":123, "History":[ 20191101, 20191112, 20191103 ] } } ] }},{ "Id":"200", "value":"Egor2", "children":{ "pilot":[ { "Properties":{ "Id":234, "History":[ 20191001, 20191012, 20191003, 20190902 ] } } ] }},{ "Id":"300", "value":"Egor3", "children":{ "pilot":[ { "Properties":{ "Id":456, "History":[ 20190901, 20190912, 20190903, 20191101 ] } } ] }}]; var result = example.filter(k=>k.children.pilot.some(d=>d.Properties.History.some(p=>input.includes(p)))); var result2 = example.filter(k=>k.children.pilot.some(d=>input.includes(d.Properties.History[0]))); console.log(result2); //console.log(result);
According to the exmaple object pilot is an array so the filter should be something like this:根据示例 object 飞行员是一个数组,所以过滤器应该是这样的:
const result = example.filter((task) =>
task.children.pilot[0].properties.history.includes(
getPbfValueByFilter(task.children, input)
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.