在AngularJS中使用ngCSV之前操作数组

时间:2015-08-29 13:45:31

标签: javascript arrays angularjs

我有一个我想要变成CSV文件的数组。看起来像这样:

filteredRecords [
{
    date: '', 
    time: '', 
    comments: [
        {message: '',
        commenttime: ''},
        {message: '',
        commenttime: ''},
        {message: '',
        commenttime: ''}
    ],
    arrival: '',
},
{
    date: '', 
    time: '', 
    comments: [
        {message: '',
        commenttime: ''},
        {message: '',
        commenttime: ''},
        {message: '',
        commenttime: ''}
    ],
    arrival: '',
}
]

ngCSV就像普通数组的魅力一样,但它无法处理嵌套数组。

我想将注释中的嵌套数组转换为字符串,因此我可以使用ngCSV导出文件,并在导入文件时执行相反操作。

它应该是这样的:

filteredRecords [
{
    date: '', 
    time: '', 
    comments: '[{"message":"test","commenttime":"16.29"},{"message":"test","commenttime":"16.29"}]',
    arrival: '',
}

我尝试过以下方法:

$scope.commenttoJson = function(filteredRecords){
        $scope.json = angular.toJson(filteredRecords);
        console.log($scope.json);
}

但是这会将整个 filteredRecords 数组转换为Json对象。

如何设法仅操纵评论对象?

1 个答案:

答案 0 :(得分:1)

这样的东西对你有用吗?



var filteredRecords = [
{
    date: '', 
    time: '', 
    comments: [
        {message: '',
        commenttime: ''},
        {message: '',
        commenttime: ''},
        {message: '',
        commenttime: ''}
    ],
    arrival: '',
},
{
    date: '', 
    time: '', 
    comments: [
        {message: '',
        commenttime: ''},
        {message: '',
        commenttime: ''},
        {message: '',
        commenttime: ''}
    ],
    arrival: '',
}
];

var newArr = [];

for (var i = 0; i < filteredRecords.length; i++) {
  newArr.push(filteredRecords[i]);
  if (newArr[newArr.length - 1].comments) {
    newArr[newArr.length - 1].comments = JSON.stringify(newArr[newArr.length - 1].comments);
  }
}

alert(JSON.stringify(newArr));
&#13;
&#13;
&#13;