Deleting Object Keys And Reassign Different Keys Is Good Approach On Iteration Of Thousands Of Objects Loop?
Solution 1:
The fastest way is to iterate them with raw for
loop:
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (item.hasOwnProperty('umra')) {
item.age = item.umra;
delete item.umra;
}
...
}
If there is too much to process, the array can be processed in chunks, separated with zero timeouts. This allows to not block main thread with lengthy loop. Intermediate setTimeout
or other async functions should run with ngZone.runOutsideAngular
in Angular to not trigger change detection:
constCHUNK_LENGTH = 1000;
ngZone.runOutsideAngular(async () => {
for (let i = 0; i < arr.length; i++) {
if (i > 0 && !(i % CHUNK_LENGTH)) {
// new chunkawaitnull;
}
const item = arr[i];
if (item.hasOwnProperty('umra')) {
item.age = item.umra;
delete item.umra;
}
// ...
}
return arr;
})
.then(arr => {
// .then triggers change detection after runOutsideAngular
})
Since promises have some overhead, it makes sense to switch to raw for
and setTimeout
for smaller chunks.
Compute-intensive tasks are supposed to be performed in web workers, but this is not the case, since there's not much computation, and same amount of loop cycles has to be performed after receiving results from web worker.
The efficient way is to not let this happen. If the object is received from API request and requires to be processed, API possibly should be changed.
Solution 2:
Use Web Workers to prevent UI from Freezing
var worker = run(function() {
// Better than using if else for each keyvar keyMaps = {
a: "x",
b: "y",
c: "z"
};
// Start when objects are available
onmessage = function(e) {
objs = e.data;
// Loop through each object of objects list
objs = objs.map(function(obj) {
var o = {};
// Loop through each key in each objectfor (k in obj) {
o[keyMaps[k]] = obj[k]
}
return o;
});
// Let the main program know about the transformationpostMessage(objs);
self.close();
};
});
// Just a wrapper to help create a Web Workerfunctionrun(func) {
returnnewWorker(URL.createObjectURL(newBlob([`(${func})()`])));
}
// Response from APIvar objs = [{
a: 1,
b: 2,
c: 3
},
{
a: 4,
b: 5,
c: 6
}
];
// Pass in objs received from API
worker.postMessage(objs);
// Do whatever you want with the output
worker.onmessage = event =>console.log(event.data);
Explanation:
- It doesn't matter if the objects are laid out flat, or nested within each other. The program will need to traverse each property
(p)
of each object{o}
. There's no way to avoidO(o * p)
time complexity. - Each object needs to be traversed, and within each object, each property needs to be traversed.
- And only way to prevent UI from freezing is to write the logic within a Web Worker.
- Use key map instead of if-else or switch statements, makes life easier!
Post a Comment for "Deleting Object Keys And Reassign Different Keys Is Good Approach On Iteration Of Thousands Of Objects Loop?"