How to export JavaScript array info to csv (on client side)?

前端 未结 29 1735
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 21:55

I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which loo

29条回答
  •  时光取名叫无心
    2020-11-21 22:38

    There are two questions here:

    1. How to convert an array to csv string
    2. How to save that string to a file

    All the answers to the first question (except the one by Milimetric) here seem like an overkill. And the one by Milimetric does not cover altrenative requirements, like surrounding strings with quotes or converting arrays of objects.

    Here are my takes on this:

    For a simple csv one map() and a join() are enough:

        var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];
        var csv = test_array.map(function(d){
            return d.join();
        }).join('\n');
    
        /* Results in 
        name1,2,3
        name2,4,5
        name3,6,7
        name4,8,9
        name5,10,11
    

    This method also allows you to specify column separator other than a comma in the inner join. for example a tab: d.join('\t')

    On the other hand if you want to do it properly and enclose strings in quotes "", then you can use some JSON magic:

    var csv = test_array.map(function(d){
           return JSON.stringify(d);
        })
        .join('\n') 
        .replace(/(^\[)|(\]$)/mg, ''); // remove opening [ and closing ]
                                       // brackets from each line 
    
    /* would produce
    "name1",2,3
    "name2",4,5
    "name3",6,7
    "name4",8,9
    "name5",10,11
    

    if you have array of objects like :

    var data = [
      {"title": "Book title 1", "author": "Name1 Surname1"},
      {"title": "Book title 2", "author": "Name2 Surname2"},
      {"title": "Book title 3", "author": "Name3 Surname3"},
      {"title": "Book title 4", "author": "Name4 Surname4"}
    ];
    
    // use
    var csv = data.map(function(d){
            return JSON.stringify(Object.values(d));
        })
        .join('\n') 
        .replace(/(^\[)|(\]$)/mg, '');
    

提交回复
热议问题