如何使用angular foreach返回值?

时间:2019-02-27 19:25:21

标签: javascript angularjs

从angular forEach返回值时,我遇到了一些问题。

这是我的数据:

vm.memberDetails={
    "member": [
        {
            "firstName": "HARRY UTTWO",
            "lastName": "POTTER",
        }
    ],
    "User": [
        {
            "memberId": 7586671,
            "customerId": 7586671,
            "customerStatus": "T",
            "firstName": "HEMOOINE",
            "lastName": "POTTER",
        },
    ]
}

vm.mockData = {
    "data": [{
        "memberNo": 7586671,
        "suffix": "A"
    }]
}

这里我需要比较memberId并从第一个数据中获取名称。我使用了angular.forEach,但是对于名称我需要使用
vm.memberDetails.User[0].firstName,但仅返回带有循环的值。

控制器:

angular.forEach(vm.memberDetails.User, function (value1,key1) {
    angular.forEach(vm.mockData, function (value2,key2) {
        if (value1.memberId === value2.memberNo) {

            vm.some= vm.memberDetails.User[0].firstName;
        }
    });
});
return vm.some;

任何帮助将不胜感激。 谢谢。

2 个答案:

答案 0 :(得分:0)

您似乎需要从vm.mockData中获取数据数组,因此将行angular.forEach(vm.mockData, function (value2,key2) { 更改为 angular.forEach(vm.mockData.data, function (value2,key2) {

angular.forEach(vm.memberDetails.User, function (value1,key1) {
    angular.forEach(vm.mockData.data, function (value2,key2) {
        if (value1.memberId === value2.memberNo) {
            vm.some= vm.memberDetails.User[0].firstName;
        }
    });
});
return vm.some;

答案 1 :(得分:0)

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
</head>
<body ng-controller="mCon">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.7/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', []);
        app.controller('mCon', function(){
            var vm = this;
            vm.memberDetails = {
         "member": [{
          "firstName": "HARRY UTTWO",
          "lastName": "POTTER",
         }],
         "User": [{
          "memberId": 7586671,
          "customerId": 7586671,
          "customerStatus": "T",
          "firstName": "HEMOOINE",
          "lastName": "POTTER",
         }, ]
        }
        vm.mockData = {
         "data": [{
           "memberNo": 7586671,
           "suffix": "A",
         }
         ]
        }
        angular.forEach(vm.memberDetails.User, function (value1,key1) {
            angular.forEach(vm.mockData.data, function (value2,key2) {
                if (value1.memberId === value2.memberNo) {
                    vm.some= vm.memberDetails.User[0].firstName;
                }
            });
        });
        return vm.some;
        })

    </script>
</body>
</html>