I am currently working on displaying objects by filtering them in my program. Upon receiving an array of objects, each containing key-value pairs, I aim to order this array based on a specific key.
For example, here is the structure of one object:
Object {
assembly_id: 1234
installation_id: "29537"
interval: "600"
itedef_id: "239"
item_id: "14485"
object_id: "114"
name: "moa"
}
My objective is to rearrange the array into arrays of objects sorted by 'object_id'. To achieve this, I have implemented a function called transformArray which groups the objects based on the specified field:
transformArray(array: Array<any>, field: string) {
if (array) {
const groupedObj = array.reduce((prev, cur) => {
if (!prev[cur[field]]) {
prev[cur[field]] = [cur];
} else {
prev[cur[field]].push(cur);
}
return prev;
}, {});
return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
}
return [];
}
This function successfully provides output with objects sorted by 'object_id' as follows:
Array(7) :[ 0: Object { key: "114", value: (11) […] } 1: Object { key: "115", value: (10) […] } 2: Object { key: "116", value: (5) […] } 3: Object { key: "117", value: (15) […] } 4: Object { key: "118", value: (13) […] } 5: Object { key: "119", value: (12) […] } 6: Object { key: "120", value: (10) […] } ]
Now, I face a challenge where objects within the arrays share the same 'assembly_id' and need to filter these objects based on 'item_id' and 'interval'. My goal is to refine the filtering process to achieve an output structured like:
Array :[
0: Object { objectIdKey: "114", value [assemblyIdKey: 2, value: [object...], assemblyIdKey: 3, value. [object...] }
1: Object { objectIdKey: "115", value: [assemblyIdKey: 5, value: [object...], assemblyIdKey: 4, value. [object...] }
2: Object { key: "objectIdKey", value: [assemblyIdKey: 6, value: [object...], assemblyIdKey: 7, value. [object...] }
]
Any tips, advice, or clues on how to improve this process are greatly appreciated. Thank you!
Cheers
Upon attempting to apply the transformArray function at a second level, it generates separate arrays for each object_id instead of achieving the desired outcome. Further refinement is needed.