Converting JSON object to CSV format in JavaScript

前端 未结 9 816
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 04:37

I am trying to convert a JavaScript object set in to CSV format

You can get the idea about my Javascript object, if you put it in online JSON parser http://json.pars

9条回答
  •  佛祖请我去吃肉
    2020-11-30 05:23

    Here's a solution similar to mightybruno's answer that handles strings containing commas. None of the other answers seem to take this in to consideration.

    function objectsToCSV(arr) {
        const array = [Object.keys(arr[0])].concat(arr)
        return array.map(row => {
            return Object.values(row).map(value => {
                return typeof value === 'string' ? JSON.stringify(value) : value
            }).toString()
        }).join('\n')
    }
    

提交回复
热议问题