如何将数组数组转换为angularjs中的对象数组?

时间:2015-10-14 05:57:12

标签: javascript angularjs

这是我的代码

$scope.students=[];

$scope.students[[object Object][object Object]]
               [0]{"id":"101","name":"one","marks":"67"}
               [1]{"id":"102","name":"two","marks":"89"}

我想转换成以下格式,如。

$scope.students=[{"id":"101","name":"one","marks":"67"},{"id":"102","name":"two","marks":"89"}]

我尝试使用.map函数但不工作,现在我想通过使用angularjs将数组数组转换为对象格式数组。

1 个答案:

答案 0 :(得分:0)

如果students变量是二维数组,如下所示:

students = [[{"id":"101","name":"one","marks":"67"}, {"id":"102","name":"two","marks":"89"}]]

您可以执行双循环以遍历每个对象数组,然后将每个对象推送到要将其保存到的数组中。下面是vanilla JavaScript,但我确信有不同的方法可以做到。

var students = [];
var results = [];

students = [[{"id":"101","name":"one","marks":"67"}, {"id":"102","name":"two","marks":"89"}]]

console.log(students); //array of array
console.log('-----'); 
console.log(students[0]); //array of object
console.log('-----'); 
for (i = 0; i < students.length; i++) { 
    console.log(students[i]); //the array of object

  for(var j=0; j < students[i].length; j++){
    results.push(students[i][j]);  
  }
}
console.log('--Results---');
console.log(results);

同时检查我的JSBin:https://jsbin.com/tareku/edit?html,js,console