Lodash 附加逗号

Lodash appending a comma

我似乎无法弄清楚这一点,我正在使用 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 中的样子:

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

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

这是您要找的吗?

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/