Lodash附上一个逗号

时间:2015-01-13 17:54:19

标签: javascript csv lodash

我似乎无法想出这个,我正在使用lodash从一个对象创建一个csv字符串,我期待输出看起来像这样:

data:text/csv;charset=utf-8,prop1,prop2,props
d1,d2,n1;n2,d3
d4,d5,n2;n3,d6
d7,d8,n4;n5,d9

但我得到的是:

data:text/csv;charset=utf-8,prop1,prop2,props
d1,d2,n1;n2,d3
,d4,d5,n2;n3,d6
,d7,d8,n4;n5,d9

这是excel中的外观:

enter image description here

以下是一些演示此问题的简化代码:

var csvContent = "data:text/csv;charset=utf-8,prop1,prop2,props\n",
data = [
    {prop1: "d1", prop2: "d2", props: [{name: "n1"},{name: "n2"}], prop3: "d3" },
    {prop1: "d4", prop2: "d5", props: [{name: "n2"},{name: "n3"}], prop3: "d6" },
    {prop1: "d7", prop2: "d8", props: [{name: "n4"},{name: "n5"}], prop3: "d9" }
];
csvContent +=_.map(data, function(rs) {
    var tmp = {};
    tmp.prop1 = rs.prop1;
    tmp.prop2 = rs.prop2;
    tmp.props = _.map(rs.props, function(r) { return r.name; }).join(';');
    tmp.prop3 = rs.prop3;
    return _.values(tmp).join(",") + '\n';
});
console.log(csvContent);

jsfiddle

1 个答案:

答案 0 :(得分:1)

这是你正在寻找的吗?

var csvContent = "data:text/csv;charset=utf-8,prop1,prop2,props\n",
data = [
    {prop1: "d1", prop2: "d2", props: [{name: "n1"},{name: "n2"}], prop3: "d3" },
    {prop1: "d4", prop2: "d5", props: [{name: "n2"},{name: "n3"}], prop3: "d6" },
    {prop1: "d7", prop2: "d8", props: [{name: "n4"},{name: "n5"}], prop3: "d9" }
];

stuff = _.map(data, function(rs) {
    var tmp = {};
    tmp.prop1 = rs.prop1;
    tmp.prop2 = rs.prop2;
    tmp.props = _.map(rs.props, function(r) { return r.name; }).join(';');
    tmp.prop3 = rs.prop3;
    return _.values(tmp).join(",");
});

csvContent += stuff.join('\n');

console.log(csvContent);

我认为问题在于您尝试添加csvContent(字符串)和_.map(...)(数组)。相反,您应该使用\n加入数组,并将其添加到csvContent

http://jsfiddle.net/85ast7n1/1/