简体   繁体   English

如何在angularjs中将对象推送到数组?

[英]How to push object to array in angularjs?

This is my code 这是我的代码

$scope.studentDetails=[];

   $scope.studentIds={};
   $scope.studentIds[0]{"id":"101"}
   $scope.studentIds[1]{"id":"102"}
   $scope.studentIds[2]{"id":"103"}

in the above code when i select student id:101 i got marks from services like 在上面的代码中,当我选择学生id:101我从诸如

   $scope.studentMarks={};
   $scope.studentMarks[0]{"marks":"67"}
   $scope.studentMarks[1]{"marks":"34"}

next i select student id:102 i got marks from services like 接下来我选择学生id:102我从类似的服务中获得了分数

   $scope.studentMarks={};
   $scope.studentMarks[0]{"marks":"98"}
   $scope.studentMarks[1]{"marks":"85"}

finally i want to store student details in to one array like 最后我想将学生详细信息存储在一个数组中

$scope.studentDetails=[{"id":"101","marks":[67,34]},{"id":"102","marks":[98,85]}] 

using angularjs. 使用angularjs。

Seems like its more of a JS question than angular. 似乎它更多的是一个JS问题,而不是角度问题。

What about the Javascript push method? Javascript push方法呢?

$scope.studentDetails.push({id: 101, marks: [67, 34]});

You can use Array.push to add one object, or concat, to concat array into another array. 您可以使用的Array.push添加一个对象,或CONCAT,到CONCAT阵列到另一个阵列。 See the references. 请参阅参考资料。

angularJS is just a library to extend Javascript. angularJS只是扩展Javascript的库。 You push into an array just like you would any object in Javascript. 您可以像使用Javascript中的任何对象一样将其压入数组。

First off, you need to declare an array. 首先,您需要声明一个数组。

$scope.studentIds = []; // Array of student ids.

Then when you want to add, you push: 然后,当您要添加时,请按:

$scope.studentIds.push({id: "101"});

To do this naively you need to loop through the student ids and then loop through the marks object and adding it to your studentDetails object if the ids match: 要天真地做到这一点,您需要遍历学生ID,然后遍历marks对象,如果ID匹配,则将其添加到您的StudentDetails对象中:

var studentDetails = [];

for (var id in studentIds) {
    var studentDetail = {}; // this will be a single student
    var marks = [];    

    if (studentIds.hasOwnProperty(id)) {
        for (var mark in studentMarks) {
            if (studentMarks.hasOwnProperty(mark) && mark.id === id) {
                studentDetail.id = id;
                marks.push(mark.marks);
            }
        }
        studentDetail.marks = marks;
    }
    studentDetails.push(studentDetail);
}

$scope.studentDetails = studentDetails;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM