Home > database >  I have an object in react javascript T[] and need to convert it to Blob
I have an object in react javascript T[] and need to convert it to Blob

Time:07-01

I am creating this js function:

export function convertArrayObjToFileDownload(data, filename, filetype = 'application/octet-stream') {
    const blob = new Blob(data, { type: filetype });
    downloadBlob(blob, filename);
}

data is a custom object array, like {Client: 'My Bank', Tasks: 15, Charge Amount: '$300.00' }.

I am trying to convert this object array to blob. The array could have hundreds of items.

CodePudding user response:

You're very close! Here's the problem:

The Blob() constructor accepts an Array as the first parameter:
https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters

And the Array needs to contain a serialized representation of the data you want to store. For a JavaScript object, that's typically JSON. So first convert your data object to a JSON string, and then store that string in the Blob:

const json = JSON.stringify(data);
const blob = new Blob([json], { type: 'text/plain;charset=utf-8' })

Since you'll be storing a string (encoded at UTF-8 by default), I'd recommend using the text/plain;charset=utf-8 MIME type.

Once you download this Blob, it'll be easy to open in any text editor since it's just plaintext.

  • Related