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