【问题标题】:How to access the ID or name in an object array which is in another array?如何访问另一个数组中的对象数组中的 ID 或名称?
【发布时间】:2019-03-20 03:38:14
【问题描述】:

我正在尝试循环以从另一个数组中的数组中的对象中获取所有ids 和names。即使我尝试使用以下方式从 1 个特定对象中抓取,它也会给我“未定义”:

companies[0][0]['id']

这是我的数组:

控制器:

app.controller('HomeController', ['$scope', 'companies', function($scope, companies) {

    $scope.companies = companies;
        console.log('companies', $scope.companies);

}]);

而且我什至不确定如何使用表达式在 HTML 中显示/访问它:

<div class="container" ng-controller="HomeController">
    <div ng-repeat="company in companies" class="list">
        <a href="#/{{ company.id }}" class="company-name">
        {{ company.name }}
    </div>
</div>

更新

工厂:

app.factory('companies', ['$http', function($http) {
    data = [];
    for (let i = 1; i < 11; i++) {
        $http.get('https://examplepage.com/wp-json/wp/v2/categories?per_page=50&page=' + i)
        .then(function(response) {
            data.push(response.data);
            console.log('data', data);
        },
        function(err) {
            return err;
        });
    }
    return data;
}]);

【问题讨论】:

    标签: javascript arrays angularjs json javascript-objects


    【解决方案1】:

    编辑(根据问题更新

    问题

    控制器与工厂之间的交互设计方式脆弱且容易出错。请参阅下面注释的代码:

    // factory
    app.factory('companies', ['$http', function($http) {
        data = [];
        for (let i = 1; i < 11; i++) {
            // you CANNOT control when this is going to return
            $http.get('https://examplepage.com/wp-json/wp/v2/categories?per_page=50&page=' + i)
            .then(function(response) {
                // so this doesn't push to `data` synchronously, this DOES NOT
                // guarantee you when you return data, every response.data will be there
                data.push(response.data);
                console.log('data', data);
            },
            function(err) {
                return err;
            });
        }
        // this will always be returned empty ([], as you initialized it) because
        // the async responses (commented above) haven't arrived when this lint his hit.
        return data;
    }]);
    
    // controller
    $scope.companies = companies; // so, companies will always be [] (empty array)
    

    解决方案

    您应该强烈考虑将实现工厂的方式更改为如下方式:

    想法

    • 不调用端点x(11)次获取550个项目(50 * 11次)
    • 在工厂中提供一个函数(getCompanies),它接受一个itemsPerPage 和一个page 参数,这样你就可以在你想要的页面中获取尽可能多的项目。即:要获得 550 个项目,您应该调用它:companies.getCompanies(550);
    • 任何想要联系公司的控制者拨打companies.getCompanies

    代码

    // factory
    app.factory('companies', ['$http', function($http) {
    
        function fnGetCompanies(itemsPerPage, page) {
            var ipp = itemsPerPage || 50; // 50 default
            var page = page || 0; // 0 default page
            // return the promise instead of data directly since you cannot return the value directly from an asynchronous call
            return $http
                .get('https://examplepage.com/wp-json/wp/v2/categories?per_page=' + ipp + '&page=' + page)
                .then(
                    function(response) {
                        // and then return the data once the promise is resolved
                        return response.data;
                    },
                    function(err) {
                        return err;
                    }
                );
        }
        // provide a `getCompanies` function from this factory
        return {
            getCompanies: fnGetCompanies
        }
    }]);
    
    // controller
    // get 550 items starting from 0
    companies.getCompanies(550, 0).then(function(companies) {
        $scope.companies = companies;
    });
    

    补充说明

    记住You cannot return from an asynchronous call inside a synchronous method


    原帖

    您可以先使用Array.prototype.reduce 将多数组结构转换为单个数组,如下所示:

    $scope.companies = companies.reduce(function(prevArr, currentArr) { return prevArr.concat(currentArr);}, []);
    

    这会转换这样的结构:

    [
     [{id: 1, name: 'A'}, {id: 2, name: 'B'}, {id: 3, name: 'C'}],
     [{id: 4, name: 'D'}, {id: 5, name: 'E'}, {id: 6, name: 'F'}]
    ];
    

    进入这个:

    [{"id": 1,"name": "A"},{"id": 2,"name": "B"},{ "id": 3,"name": "C"},{"id": 4,"name": "D"},{"id": 5,"name": "E"},{"id": 6,"name": "F"}]
    

    简单演示:

    var companies =[
     [{id: 1, name: 'A'}, {id: 2, name: 'B'}, {id: 3, name: 'C'}],
     [{id: 4, name: 'D'}, {id: 5, name: 'E'}, {id: 6, name: 'F'}]
    ];
    
    console.log(companies.reduce(function(prev, current) { return prev.concat(current);}, []));

    【讨论】:

    • 这是有道理的,但是当我尝试执行它时,当$scope.companies 被控制台记录时,我得到一个空数组
    • @hkhuu 那么还有一个问题,你的原始帖子中没有说明,伙计。 $scope.companies = companies; 是否在异步代码中?
    • 我想可能是这样。它是从我在一个单独的 js 文件中拥有的工厂中提取的。我已经用该代码更新了我的原始帖子。有机会请看一下,谢谢!
    • @hkhuu,嗯......哇......这是一个完全不同的问题......让我看看。
    • 哇,非常感谢您的分解!我真的很感激!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    相关资源
    最近更新 更多