如何在没有键的情况下将json转换为angularjs中的数组?

时间:2016-06-14 12:38:37

标签: angularjs

在我的代码json中返回这样的格式

 var data = [
     {"field1":"918666400041","field2":"2016-05-19 11:52:52"},
     {"field1":"918666400035","field2":"2016-05-19 11:52:52"},
     {"field1":"918666400060","field2":"2016-05-19 11:52:52"}
 ];

但我需要使用以下键转换为数组格式:

 var Data = [
     ['918666400041', '2016-05-19 11:52:52'],
     ['918666400035', '2016-05-19 11:52:52'],
     ['918666400035', '2016-05-19 11:52:52']
 ];

任何人都可以为这个问题提供解决方案吗?

我已尝试使用angular.forEach函数和map函数,但我没有获得此格式。

6 个答案:

答案 0 :(得分:2)

 var obj = [ {"field1":"918666400041","field2":"2016-05-19 11:52:52"}, {"field1":"918666400035","field2":"2016-05-19 11:52:52"}, {"field1":"918666400060","field2":"2016-05-19 11:52:52"} ];

var res = obj.map(function(val) {
   return [val.field1, val.field2]
})

console.log(res)

答案 1 :(得分:2)

根据您想要support的浏览器,您可以使用ES5 map功能:

var mappedData = data.map(function(obj) { 
    return [obj.field1, obj.field2]; 
});

如果您无法访问ES5数组方法,可以使用angular的forEach,如下所示:

var mappedData = [];
angular.forEach(data, function(obj) { 
    mappedData.push([obj.field1, obj.field2]); 
});

答案 2 :(得分:1)

试试这个

var data = [
{"field1":"918666400041","field2":"2016-05-19 11:52:52"},
{"field1":"918666400035","field2":"2016-05-19 11:52:52"},
{"field1":"918666400060","field2":"2016-05-19 11:52:52"}
];

var x =[];

angular.forEach(data,function(val,index){
x.push(val.field1)
x.push(val.field2)
})

现在在x中你将获得所需的数组

答案 3 :(得分:0)

您可以尝试reduce功能:

var Data = data.reduce(function(previousValue, currentValue) {
    previousValue.push([currentValue.field1, currentValue.field2])
    return previousValue;
}, []);

答案 4 :(得分:0)

你可以这样:

var l_IN = <your starting JSON> ;

var I_OUT = [] ;

for (x = 0 ; x < l_IN.length ; x++) {

    dummy = {l_IN.field1,l_IN.field2} ;

    l_OUT.push(dummy) ;

// or l_OUT.push(l_IN.field1,l_IN.field2) ;
}

....

答案 5 :(得分:0)

您可以使用以下内容:

preferencesObj.saveThePreferences(contextOfApplication);

这与Converting JSON Object into Javascript array

非常相似(但有点复杂)