配对AngularJS中数组的类似对象

时间:2017-08-04 16:21:36

标签: javascript angularjs arrays

我有一个名为routerList的数组中的路由器列表。我想在我的视图中显示备份路由器旁边的活动路由器。数组中的路由器对象具有名为HostName的属性,该属性具有locationID_Router#_RouterName,例如WA34_R01_ABCABC。阵列中的某个位置是另一个路由器,其名称为WA34_R02_ABCABC。我想重新排序数组,所以当我使用ng-repeat时,这两个路由器和所有其他匹配的对将彼此相邻。我写了一个函数,告诉我名字是否相同减1个字符,所以R01和R02。这里:

        function stringCompare(word1, word2){
        var differences = 0;
        if(word1 != word2){
            if(word1.length == word2.length){
                for(i=0; i <= word1.length-1; i++){
                    if(word1.charAt(i) != word2.charAt(i)){
                        differences +=1;
                    }
                }
            }
        }
        if(differences == 1){
            return true;
        }else{
            return false;
        };
    };

然后我尝试在循环中有一个循环来获取对并将它们添加到一个新数组,因为它找到了对,但我不断得到错误,无法通过循环读取HostName。

function findCouples(array){
            var MatchedRouters = [];
            for(i=0;i<=array.length-1;i++){
                for(var i2=0;i2<=array.length-1;i2++){
                    if(stringCompare(array[i].HostName,array[i2].HostName)){
                        MatchedRouters.push(array[i]);
                        MatchedRouters.push(array[i2]);
                    }
                }
            }
            return MatchedRouters
        };

如果有更好的方法,请告诉我!如果没有任何帮助你可以给我让它工作,这样会很惊人。 谢谢!

1 个答案:

答案 0 :(得分:1)

当您初步获取列表或路由器时,请创建您需要排序的属性。

类似的东西:

routers.forEach(function(router) {
    router.location: getRouterLocation(router.HostName);
    router.number: getRouterNumber(router.HostName);
    router.name: getRouterName(router.HostName);
});

然后创建你的函数getRouterLocation,getRouterNumber等来解析你需要的值。

function getRouterLocation(hostName) {
    return hostName.substring(0, hostName.indexOf('_');
}