简体   繁体   中英

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

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.

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, I'd recommend using the text/plain;charset=utf-8 MIME type or application/json for JSON specifically.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM