I have an array of objects. I want to remove Fields which have columns has null. It has to separate into two different arrays which has columns data another has does not have columns
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"
}
]
}
]
}
]
I tried to filter the objects but unable to get parent object along with it, to be precise GroupName is missing
groupItems.map(item=>item.Fields.filter(k=>k.Columns!==null))
I am expecting two different arrays as output
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"
}
]
}
]
}
]
>Solution :
You can use map with destructuring to extract fields:
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);