UPDATE I stumbled upon a potential solution that I have appended to my question and am now seeking a more refined approach.
In the context of an Angular 9 application, I am working with a two-dimensional array that I need to restructure. Through my use of RxJS operators, I have achieved some degree of success in this task.
The objective is to group all the data with the property _id by their respective row numbers under a parent level property called dataset. Additionally, I aim to include properties such as iconDefault and row.
While I can achieve this goal using traditional looping techniques, I want to leverage RxJS further for a better understanding.
This is my initial 2D array:
[
[
{
"_id": "5efbb97e80752985301c3447",
"row": 1,
"position": 0,
"tab": 1
},
{
"_id": "5efbb97e80752985301c3453",
"row": 1,
"position": 1,
"tab": 1
}
],
[
{
"_id": "5efbb97e80752985301c3411",
"row": 2,
"position": 0,
"tab": 1
},
{
"_id": "5efbb97e80752985301c3414",
"row": 2,
"position": 1,
"tab": 1
},
{
"_id": "5efbb97e80752985301c33f3",
"row": 2,
"position": 2,
"tab": 1
}
],
[
{
"_id": "5efbb97e80752985301c343b",
"row": 3,
"position": 0,
"tab": 1
}
]
]
The desired end result:
{
"tab": 1,
"dataset": [{
"row": 1,
"iconDefault": "5e7824c67bd78eb199e95f3e",
"ids": ["5efbb97e80752985301c3447",
"5efbb97e80752985301c3453"
]
}, {
"row": 2,
"iconDefault": "5e7824c67bd78eb199e95f3e",
"ids": ["5efbb97e80752985301c3411",
"5efbb97e80752985301c3414",
"5efbb97e80752985301c33f3"
]
}, {
"row": 3,
"iconDefault": "5e7824c67bd78eb199e95f3e",
"ids": ["5efbb97e80752985301c343b"]
}]
}
The best current outcome I could generate:
{
"dataset": [
[
"5efbb97e80752985301c3447",
"5efbb97e80752985301c3453"
],
[
"5efbb97e80752985301c3411",
"5efbb97e80752985301c3414",
"5efbb97e80752985301c33f3"
],
[
"5efbb97e80752985301c343b"
]
],
"tab": 1
}
I have defined the source 2D array and applied the following code to produce my existing output
// source defined from 2d array shown above
let updatePackage = {};
updatePackage.dataset = source.map((subarray) =>
subarray.map((row) => row._id)
);
updatePackage.tab = 1; //manually set but ideally obtained from relevant data
console.log(updatePackage);
document.body.append(JSON.stringify(updatePackage));
An alternative solution based on OCD tendencies:
let updatePackage = {} as any;
updatePackage.tab = 1;
let dataset = [] as any;
dataset = this.rows.map((subarray) => subarray.map((row) => row._id));
updatePackage.dataset = dataset.map((row, rowIndex = 0) => {
rowIndex++;
return {
row: rowIndex,
ids: row,
iconDefault: '5e7824c67bd78eb199e95f3e',
};
});