将对象数组更改为CSV模式

时间:2014-10-14 02:45:19

标签: javascript arrays loops object csv

我有以下数组:

var objRow = [
    {
        2011-09-20 : [0, 100, 0],
        customerID : C1101,
        ANI : 1234
    },
    {
        2011-09-25 : [0, 0, 0],
        customerID : C1101,
        ANI : 1234
    },
    {
        2011-09-20 : [0, 500, 0],
        customerID : C1102,
        ANI : 5678
    },
    {
        2011-09-22 : [0, 0, 50],
        customerID : C1102,
        ANI : 5678
    }
]

我想从上面的数组创建CSV数据。但是,我有问题将该数组更改为此CSV模式:

1234, C1101, 0, 0, 100, 0, 0, 0
5678, C1102, 0, 0, 500, 0, 0, 50

我尝试使用 reduce customerID进行分组,因为每个对象中的第一个索引都是日期。我有一些日期:

var dateArr = ["2011-09-20", "2011-09-22", "2011-09-25"];

这是我的代码:

var result = objRow.reduce(function(prev, curr, index, arr) {
    var num = curr["customerID"];

    if (!prev[num]) {
        prev[num] = [];
    }

    for (var j = 0; j < dateArr.length; j++) {
        prev[num].push(curr[dateArr[j]]);
    }

    return prev;
}, {});

更新问题 对于date索引中的数字组合。我使用这个规则:

[0, 100, 0] // from first Object
[0, 0, 0] // from second Object


fistObject_firstIndex, secondObject_firstIndex, firstObject_secondIndex, secondObject_secondIndex, firstObject_thirdIndex, secondObject_thirdIndex
0, 0, 100, 0, 0, 0

向上,向下,向上,向下,向上,向下......

如何在上面创建CSV模式? 谢谢......

2 个答案:

答案 0 :(得分:1)

我认为这会给你想要的结果:

&#13;
&#13;
var objRow = [{
  date: 2011-09-20,
  nums: [0, 100, 0],
  customerID: "C1101",
  ANI: 1234
}, {
  date: 2011-09-25,
  nums: [0, 0, 0],
  customerID: "C1101",
  ANI: 1234
}, {
  date: 2011-09-20,
  nums: [0, 500, 0],
  customerID: "C1102",
  ANI: 5678
}, {
  date: 2011-09-22,
  nums: [0, 0, 50],
  customerID: "C1102",
  ANI: 5678
}];


//CREATE CSV-FORMATTED STRINGS
var csvLine = "";
var numsArray = new Array();
for (var i=0; i<objRow.length; i++) {
  //check if this is the first element with a new 'ANI' (which means a new CSV line starts)
  if (objRow[i-1]==(undefined||null) || objRow[i].ANI!=objRow[i-1].ANI) {
    //if so, start a new string
    csvLine = objRow[i].ANI +", "+ objRow[i].customerID +", "; //add the 'ANI' and 'customerID'
    numsArray.length = 0; //clear array
    numsArray.push(objRow[i].nums); //store the 'nums' in a separate array
  } else {
    //if not, add to the existing string
    numsArray.push(objRow[i].nums); //store the 'nums' in a separate array
  }

  //check if this is the last element with the same 'ANI' (which means this CSV line is complete)
  if (objRow[i+1]==(undefined||null) || objRow[i].ANI!=objRow[i+1].ANI) {
    //add the 'nums' of every object in intertwining order (every 1st, every 2nd, etc.)
    for (var k=0; k<numsArray[0].length; k++) {
      for (var j=0; j<numsArray.length; j++) {
        csvLine += numsArray[j][k].toString() +", ";
      }
    }
    //remove the last comma
    if (csvLine.substring(csvLine.length-2) == ", ") {
      csvLine = csvLine.substring(0,csvLine.length-2);
    }
    //output the CSV line
    document.getElementById("csv").innerHTML += csvLine + "<br />";
  }
}
&#13;
<div id="csv"></div>
&#13;
&#13;
&#13;

小提琴:http://jsfiddle.net/5gyp3ce6/16/

我不得不稍微更改一下你的阵列,因为为了这个工作,数组键需要全部相同。
另外,我必须将ID更改为字符串,否则无法定义。

最后,您可以将该行添加到另一个将其写入文件或其他任何变量的行中,而不是将其写入<div>

如果代码中的评论不够清晰,请发表评论,我会尝试更好地解释。

答案 1 :(得分:0)

尝试

var objRow = [
    {
        "2011-09-20" : [0, 100, 0],
        customerID : "C1101",
        ANI : 1234
    },
    {
        "2011-09-25" : [0, 0, 0],
        customerID : "C1101",
        ANI : 1234
    },
    {
        "2011-09-20" : [0, 500, 0],
        customerID : "C1102",
        ANI : 5678
    },
    {
        "2011-09-22" : [0, 0, 50],
        customerID : "C1102",
        ANI : 5678
    }
];

var arr = [],
    res = [],
    csv = $.map(objRow, function (v, k) {  
        // items         
        arr.push(v.ANI, v.customerID, v[Object.keys(v)[0]]);
        // arrays
        var a = $.grep(arr, function (val, index) {
            return $.isArray(val)
        });
        // strings
        var s = arr.filter(function (i) {
            return typeof i === "string"
        });
        // sort items
        res.push([arr.filter(Number)[0]
                 , s[0]
                 , a.splice(0, 2).join(",")
                 , arr.filter(Number).slice(-1)[0]
                 , s.slice(-1)[0]
                 , a.join(",")]);
        return res
    }).slice(-1)[0];
    // format text , html
    csv = (csv.slice(0, 3) + "<br>" + csv.slice(-3))
          .replace(/,/g, ", ");
    $("body").append(csv)

&#13;
&#13;
var objRow = [
    {
        "2011-09-20" : [0, 100, 0],
        customerID : "C1101",
        ANI : 1234
    },
    {
        "2011-09-25" : [0, 0, 0],
        customerID : "C1101",
        ANI : 1234
    },
    {
        "2011-09-20" : [0, 500, 0],
        customerID : "C1102",
        ANI : 5678
    },
    {
        "2011-09-22" : [0, 0, 50],
        customerID : "C1102",
        ANI : 5678
    }
];

var arr = [],
    res = [],
    csv = $.map(objRow, function (v, k) {
        arr.push(v.ANI, v.customerID, v[Object.keys(v)[0]]);
        // arrays
        var a = $.grep(arr, function (val, index) {
            return $.isArray(val)
        });
        // strings
        var s = arr.filter(function (i) {
            return typeof i === "string"
        });

        res.push([arr.filter(Number)[0], s[0], a.splice(0, 2).join(","), arr.filter(Number).slice(-1)[0], s.slice(-1)[0], a.join(",")]);
        return res
    }).slice(-1)[0]; 

csv = (csv.slice(0, 3) + "<br>" + csv.slice(-3))
      .replace(/,/g, ", ");
$("body").append(csv)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;