将对象数组更改为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

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

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模式?非常感谢。

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

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 />";
  }
}
<div id="csv"></div>

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

我不得不稍微改变一下你的数组,因为要想做到这一点,数组键必须都是相同的
此外,我必须将ID更改为字符串,否则无法定义它们。

当然,您可以将该行添加到另一个变量中,而不是在末尾将其写入<div>或其他任何变量中。

如果代码中的注释不够清晰,只需留下注释,我会尝试更好地解释它。

尝试

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)

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)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

最新更新