I need help in breaking this array of Object into a distinct arrays based on the repeated objects.
The original array is as follows:
const originalArray = {
Rows: [
{
RowValue: [
{
FieldIndex: '1',
Value: 'Sample Item One'
},
{
FieldIndex: '2',
Value: 'Sample Item Two'
},
{
FieldIndex: '3',
Value: 'Sample Item Three'
},
{
FieldIndex: '4',
Value: 'Sample Item Four'
},
{
FieldIndex: '1',
Value: 'Another Sample Item One'
},
{
FieldIndex: '2',
Value: 'Another Sample Item Two'
},
{
FieldIndex: '3',
Value: 'Another Sample Item Three'
},
{
FieldIndex: '4',
Value: 'Another Sample Item Four'
},
]
},
{
RowValue: [
{
FieldIndex: '1',
Value: 'Sample Object One'
},
{
FieldIndex: '2',
Value: 'Sample Object Two'
},
{
FieldIndex: '3',
Value: 'Sample Object Three'
},
{
FieldIndex: '4',
Value: 'Sample Object Four'
},
{
FieldIndex: '1',
Value: 'Another Sample Object One'
},
{
FieldIndex: '2',
Value: 'Another Sample Object Two'
},
{
FieldIndex: '3',
Value: 'Another Sample Object Three'
},
{
FieldIndex: '4',
Value: 'Another Sample Object Four'
},
]
}
]
}
I will like to have the result look like this
const originalArray = {
Rows: [
{
RowValue: [
{
FieldIndex: '1',
Value: 'Sample Item One'
},
{
FieldIndex: '2',
Value: 'Sample Item Two'
},
{
FieldIndex: '3',
Value: 'Sample Item Three'
},
{
FieldIndex: '4',
Value: 'Sample Item Four'
}
]
},
{
RowValue: [
{
FieldIndex: '1',
Value: 'Another Sample Item One'
},
{
FieldIndex: '2',
Value: 'Another Sample Item Two'
},
{
FieldIndex: '3',
Value: 'Another Sample Item Three'
},
{
FieldIndex: '4',
Value: 'Another Sample Item Four'
},
]
},
{
RowValue: [
{
FieldIndex: '1',
Value: 'Sample Object One'
},
{
FieldIndex: '2',
Value: 'Sample Object Two'
},
{
FieldIndex: '3',
Value: 'Sample Object Three'
},
{
FieldIndex: '4',
Value: 'Sample Object Four'
}
]
},
{
RowValue: [
{
FieldIndex: '1',
Value: 'Another Sample Object One'
},
{
FieldIndex: '2',
Value: 'Another Sample Object Two'
},
{
FieldIndex: '3',
Value: 'Another Sample Object Three'
},
{
FieldIndex: '4',
Value: 'Another Sample Object Four'
},
]
}
]
}
This is what I did, but I could not make it repeat the objects as expected;
const splitGridRows = (gridRows) => {
const newRows = [];
gridRows.forEach((gridRow) => {
let newGridRow = {};
let newRowValue = [];
gridRow.RowValue.forEach((valueObj) => {
const hasFieldData = newRowValue.find(
(rValue) => rValue.FieldIndex === valueObj.FieldIndex
);
if (!hasFieldData) {
newRowValue.push(valueObj);
newGridRow = { RowValue: newRowValue };
}
});
newRows.push(newGridRow);
});
return newRows;
};
Can someone please help me? Thanks in anticipation.