javascript - 如何访问另一个数组中的对象数组中的 ID 或名称?

标签 javascript arrays angularjs json javascript-objects

我正在尝试遍历以从数组中的对象获取所有idname,而数组又在另一个数组中。即使我尝试使用以下方法从 1 个特定对象中获取,它也会给我“未定义”:

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

这是我的数组:

enter image description here

enter image description here

Controller :

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;
}]);

最佳答案

编辑(根据问题更新)

问题

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

// 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)

解决方案

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

想法:

  • 不要为获取 550 个项目调用端点 x (11) 次(50 * 11 次)
  • 在工厂中提供一个函数(getCompanies),它接受一个itemsPerPage 和一个page 参数,这样你可以获得尽可能多的项目如您所愿,在您想要的页面中。即:要获得 550 件商品,您应该调用它:companies.getCompanies(550);
  • 从任何想要获取公司调用的 Controller 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);}, []));

关于javascript - 如何访问另一个数组中的对象数组中的 ID 或名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52821311/

相关文章:

angularjs - 在 ng-repeat 元素内的新行上的表格中显示 tr 的最后一个 td

javascript - jQuery Mobile slider 输入更改事件

php - 如何分解字符串数组并将结果存储在另一个数组中 (php)

Java:创建了多少个对象?数组作为成员变量

angularjs - 如何处理不是数组的 Restangular .getList() 响应

javascript - 在 AngularJS 中查询后运行代码

javascript - 为什么重新加载在ajax中不可见,但在控制台中可见?

javascript - 关闭模态之前保存/取消提示(当模态已通过 ESC/单击背景关闭时)

javascript - Hapi.js 限制仅访问本地主机

arrays - 在 Perl 中,如何制作数组的深层复制?