使用JS变量名称命名其他变量

时间:2015-12-24 04:11:24

标签: javascript angularjs json

我使用node来获取内部数据库工具的Swimlanes列表(作为JSON对象的数组)。

格式:

swimlanes = [{"swimlane" : "1"},{"swimlane" : "2"}, ...]

然后我检索所有MSSQL Server实例的列表(格式相同)。

instances = [{"instance" : "host\instance", "swimlane" : "1"}, ...]

我想要做的是创建一个名为slInstances的JSON对象,它将是泳道实例数组的集合。

slInstances = { "1" : ["host\instance", "host\instance"], "2" : ["host\instance", "host\instance"]

我试过了:

 function getInstancesSuccess(response){

            $scope.instances = response.data;

            $scope.slInstances = {};

            $scope.swimlanes.forEach(function(){
                var sl = this.swimlane;
                $scope.slInstances[sl] = $scope.instances.filter(function(el){
                    return el.swimlane == sl;
                })
            });
        }

(只保留"实例"在范围内,因为我将其用于其他事情)但这根本不起作用。我希望能够让sl =类似于" 1",循环通过每个泳道。因此为slInstances分配一个值[" 1"] =,slInstances [" 2"] = ....

因此,在我的角度模板中,我可以按照以下方式执行某些操作:

<ul>
    <li ng-repeat="sl in swimlanes">{{sl['swimlane']}}
        <ul>
            <li ng-repeat="i in slInstances">{{ i[sl['swimlane']].instance}}

唯一的原因我不是简单地制作一个递增的数组,并且使用这样的对象是因为我们的泳道不是连续的顺序(0,1,22,23,30,31等)所以我想要它是联想的。

我是以完全错误的方式解决这个问题吗?

谢谢!

编辑:

创建了一个要显示的plunker:

http://plnkr.co/edit/Y2PjAxzsvm201EL7mQC4

3 个答案:

答案 0 :(得分:2)

如果我理解你想要完成的事情:

var swimlanes = [{"swimlane" : "1"},{"swimlane" : "2"},{"swimlane" : "3"}];
var instances = [{"instance" : "host1/instance1", "swimlane" : "1"}, {"instance" : "host2/instance2", "swimlane" : "2"}];

var slInstances = {};

for (var i = 0; i < swimlanes.length; i++) {
    slInstances[swimlanes[i].swimlane] = [];
}


for (var i = 0; i < instances.length; i++) {
    slInstances[instances[i].swimlane].push(instances[i].instance);
}   

// returns {"1":["host1/instance1"],"2":["host2/instance2"],"3":[]}

告诉我,如果是这种情况,可以使用underscore.js使其更清洁。

答案 1 :(得分:0)

我认为这个错误是你对forEach的使用:

    scope.swimlanes.forEach(function(swimlane){
    var sl = swimlane;

答案 2 :(得分:0)

从查看代码我不明白为什么需要组合这两个数组。

第二个实例= [{“instance”:“host \ instance”,“swimlane”:“1”}]包含它的泳道。

Angulars ng-repeat将使数组中的每个项目都与自身相关联,在本例中为sl。所以sl.swimlane和sl.instance将始终来自同一个对象。

<ul>
  <li ng-repeat="sl in instances ">{{sl.swimlane]}}
    <ul>
        <li>{{sl.instance}}</li>
    </ul>
  </li>
</ul>
相关问题