如何在 React 中过滤复杂对象



我有一个像下面这样的对象。

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

]

我有一个输入20191101。有时输入可以是 20191101,20191001。我需要过滤示例,如果

children.pilot.properties.history[0]=== 20191101.

我尝试了以下方法:

const result = example.filter( task => task.children.pilot.properties.history.includes(getPbfValueByFilter(task.childen, input))
);

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;
}
});
};

预期输出 :

[
{
"Id": "100",
"value": "Egor1",
"children": {
"pilot": [
{
"Properties": {
"Id": 123,
"History": [
20191101,
20191112,
20191103
]
}
}
]
}
}
]

我正在获得控制台部分。但它无法获取结果。我假设"包含"没有按预期工作。出了什么问题。请指教。 蒂亚。

您可以将somefilter一起使用。让我知道这是否是您正在寻找的:

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);

根据示例,对象 pilot 是一个数组,因此过滤器应该是这样的:

const result = example.filter((task) =>
task.children.pilot[0].properties.history.includes(
getPbfValueByFilter(task.children, input)
)
);

最新更新