将对象数组转换为angularjs中的数组

时间:2015-03-12 02:00:53

标签: arrays angularjs

我在控制器表单中有这些数据:

 $scope.reports = [
            {
                departuredate:"2015-03-10",
                routeline:"PASAY - CAGAYAN",
                seatingtypescode:"ABS",
                tickettripcode:"3",
                tripcodetime:"16:30:00"
            },
            {
                departuredate:"2015-03-10",
                routeline:"PASAY - CAGAYAN",
                seatingtypescode:"ABS",
                tickettripcode:"3",
                tripcodetime:"16:30:00"
            }
          ];

以上数据是对象数组,我希望它们在数组中转换。我使用下面的代码将它们转换为数组:

var details=[];

        for(var index in $scope.reports){
            var tripcode = $scope.reports[index].tickettripcode;
            var dateOfDepature = $scope.reports[index].departuredate.split('-');
            details.push(tripcode, dateOfDepature[2]);
        }
if(details[tripcode][dateOfDeparture[2]]){
    details[tripcode][dateOfDeparture[2]] = details[tripcode][dateOfDeparture[2]] +1;
}
else {
    details[tripcode][dateOfDeparture[2]] =1;
}

代码对我不起作用,我不知道为什么。我怀疑我是否正在以正确的方式进行数组操作。我有错误dateOfDeparture is not defined。我已经定义了dateOfDeparture,为什么我收到此错误。我只想获得看起来像这样的输出:

    details = Array (
                [3] =>Array
                (
                    [10] =>2
                )
    )

[3]是tickettripcode,[10]是depaturdate的日子。 2表示该日期的离职人数。

非常感谢任何帮助。 这是我小提琴的链接:https://jsfiddle.net/n1bw2u36/ 提前谢谢!

1 个答案:

答案 0 :(得分:1)

不幸的是,你应该学习很多关于javascript的东西。

顺便说一下,我希望你能用这样的代码得到你想要的东西。

var reports = [
    {
        departuredate:"2015-03-10",
        routeline:"PASAY - CAGAYAN",
        seatingtypescode:"ABS",
        tickettripcode:"3",
        tripcodetime:"16:30:00"
    },
    {
        departuredate:"2015-03-10",
        routeline:"PASAY - CAGAYAN",
        seatingtypescode:"ABS",
        tickettripcode:"3",
        tripcodetime:"16:30:00"
    }
];

var table = {};

for (index=0; index<reports.length; index++){

    var tripcode = reports[index].tickettripcode;
    var dateOfDepature = reports[index].departuredate.split('-');
    var date = dateOfDepature[2];

    var map = table[tripcode];
    if (map===undefined){
        map = {};
        table[tripcode] = map;
    }

    if (map[date]===undefined){
        map[date] = 0;
    }

    map[date]++;

}

您可以像这样使用“表格”。

console.log(table);
console.log(table[3][10]);