如何将一个数组分隔为两个数组



我有一个对象数组。我想删除字段的列有null。它必须分成两个不同的数组一个有列数据另一个没有列

const groupItems = [
{
"GroupName": "CorrSection",
"Fields": [
{
"FieldName": "TemplateVersion",
"Columns": null
},
{
"FieldName": "CorrTypePrintGrps",
"Columns": [
{
"ColumnName": "CorrTypeName"
}
]
}
]
},
{
"GroupName": "RcSection",
"Fields": [
{
"FieldName": "RcVersion",
"Columns": null
},
{
"FieldName": "RcPrintGrps",
"Columns": [
{
"ColumnName": "RcName"
}
]
}
]
}
]

我试图过滤对象,但无法获得父对象随着它,确切地说,GroupName丢失

groupItems.map(item=>item.Fields.filter(k=>k.Columns!==null))

我期望输出两个不同的数组

Array_One

[
{
"GroupName": "CorrSection",
"Fields": [
{
"FieldName": "TemplateVersion",
"Columns": null
}
]
},
{
"GroupName": "RcSection",
"Fields": [
{
"FieldName": "RcVersion",
"Columns": null
}
]
}
]

Array_Two

[
{
"GroupName": "CorrSection",
"Fields": [
{
"FieldName": "CorrTypePrintGrps",
"Columns": [
{
"ColumnName": "CorrTypeName"
}
]
}
]
},
{
"GroupName": "RcSection",
"Fields": [
{
"FieldName": "RcPrintGrps",
"Columns": [
{
"ColumnName": "RcName"
}
]
}
]
}
]

您可以使用带有解构的map来提取字段:

const groupItems = [
{
"GroupName": "CorrSection",
"Fields": [
{
"FieldName": "TemplateVersion",
"Columns": null
},
{
"FieldName": "CorrTypePrintGrps",
"Columns": [
{
"ColumnName": "CorrTypeName"
}
]
}
]
},
{
"GroupName": "RcSection",
"Fields": [
{
"FieldName": "RcVersion",
"Columns": null
},
{
"FieldName": "RcPrintGrps",
"Columns": [
{
"ColumnName": "RcName"
}
]
}
]
}
]

const arr1 = groupItems.map(({ GroupName, Fields }) => ({
GroupName,
Fields: Fields.filter(({ Columns }) => Columns === null)
}));
const arr2 = groupItems.map(({ GroupName, Fields }) => ({
GroupName,
Fields: Fields.filter(({ Columns }) => Columns !== null)
}));

console.log(arr1);
console.log(arr2);

相关内容

  • 没有找到相关文章

最新更新