2017-03-08 59 views
1

在我的脚本中,我使用异步获取来获取我的对象的数据。将新属性推送到循环内的当前对象

下面是脚本:

self.organizations = []; 

Service.get(self.orgId).then(function (org) { 
    self.organizations.push({ 
     Organization: org, 
     Role: "User" 
    }); 

    Service.getGroups().then(function (result) { 
     _.forEach(result.Objects, function (res) { 
      if (res.org.Id === self.orgId) { 
       self.organizations.Groups = res.Groups; 
      } 
     }); 
    }); 
}); 

首先,我得到了组织的数据。然后,在这个承诺中,我检索所有组,并且如果一个组作为相同的组织标识,那么它就意味着组nd组织是有约束力的。

的res.Groups典范:

res.Groups = [ 
    {Id: 1, Name: "Group Name 1"}, 
    {Id: 2, Name: "Group Name 2"} 
]; 

由于其他功能不显示,我不能使用任何其他功能“架构”。

然后我想添加到self.organizations数组中,在当前组织的索引,其组。但这里的结果是,我得到:

self.organizations = [ 
    {Organization: "First Organization", Role: "User"}, 
    {Organization: "Second Organization", Role: "User"}, 
    Groups: [ 
     {Id: 1, Name: "Group Name 1"}, 
     {Id: 2, Name: "Group Name 2"} 
     {Id: 3, Name: "Group Name 3"} 
    ] 
]; 

而我想到:

self.organizations = [ 
    { 
     Organization: "First Organization", 
     Role: "User", 
     Groups: [ 
      {Id: 1, Name: "Group Name 1"}, 
      {Id: 1, Name: "Group Name 2"} 
     ] 
    }, 
    { 
     Organization: "Second Organization", 
     Role: "User", 
     Groups: [ 
      {Id: 3, Name: "Group Name 3"} 
     ] 
    } 
]; 

我不知道该怎么推res.Groups当前组织内部(目前第一承诺迭代) 。我知道我的结构可能不合适,但我努力找到一个合适的工作。

回答

1

你可以先添加Groups到当前对象,然后将其推入集合:

self.organizations = []; 

Service.get(self.orgId).then(function (org) { 
    var item = { 
     Organization: org, 
     Role: "User" 
    } 

    Service.getGroups().then(function (result) { 
     _.forEach(result.Objects, function (res) { 
      if (res.org.Id === self.orgId) { 
       item.Groups = res.Groups; 
      } 
     }); 

     self.organizations.push(item); 
    }); 
}); 
+1

感谢它的伎俩:) – BlackHoleGalaxy