Forum Moderators: open

Message Too Old, No Replies

Fun with objects, deleting an unnecessary key

         

csdude55

5:56 am on Oct 29, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have an object that looks like this:

// spaces added for readability
imgObj = [
{
"name":"20221016_153938.jpg",
"uuid":"1a58228c-6c73-4a10-9bfa-fdac88110078",
"thumbnailUrl":"https://www.example.com/1a58228c-6c73-4a10-9bfa-fdac88110078/20221016_153938.jpg"
},

{
"name":"20221016_153946.jpg",
"uuid":"b2952110-888a-4d8e-ba29-b23709f56f38",
"thumbnailUrl":"https://www.example.com/b2952110-888a-4d8e-ba29-b23709f56f38/20221016_153946.jpg"
}
]


The object is originally created for another purpose and needs all of the keys, but I also need to send it to a processing script via POST. The processing script doesn't actually NEED the "thumbnailUrl" key, though, and with the value being so long there's always a risk of losing data when the param is too long for the browser or server. So I'd like to eliminate it before sending it to the processing script.

I know that I can delete the key in a loop:

for (var i of imgObj)
delete i.thumbnailUrl;

but since this object has the potential to be pretty big, is there a better (eg, faster to process) way to delete it?

Fotiman

6:53 pm on Oct 31, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Instead of deleting the value, a more declarative approach would be to map the array of objects to objects that don't contain thumbnailUrl. Here's the "IE" friendly version:

imgObj = imgObj.map(function (img) {
return {
name: img.name,
uuid: img.uuid
};
});


And here's a version for all other modern browsers:

imgObj = imgObj.map(({ thumbnailUrl, ...rest }) => ({ ...rest }));


The native array methods, like "map", are fast.

csdude55

7:53 pm on Oct 31, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Is the second version not IE-friendly just because of the ...?

Fotiman

9:32 pm on Oct 31, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



And the arrow function.