2016-03-01 123 views
0

我有以下JSON對象,這是loopback模型(分類)的結果,與另一個模型(標籤)的關係。訪問包含的對象

我的調用來獲取分類爲:

modClassification.findOne({ 
      where: { id: classificationid }, 
      include: 'labels' }, 
      function(err, classification){ ... 

而這個返回分類的東西,如

{ id: 'b01', 
    title: 'population', 
    country_id: 1, 
    labels: 
    [ { column_id: 'b1', 
     classification_id: 'b01', 
     classification_title: 'population', 
     dsporder: 1, 
     label: 'Total_Persons_Males', 
     country_id: 1, 
     id: 1 }, 
    { column_id: 'b2', 
     classification_id: 'b01', 
     classification_title: 'population', 
     dsporder: 2, 
     label: 'Total_Persons_Females', 
     country_id: 1, 
     id: 2 } ] } 

這正是我所期望的。

我現在需要遍歷標籤並訪問它的屬性,但這是我卡住的地方。

classification.labels[0] = undefined.. 

我試過循環,每一個,無論我可以在網上找到,但似乎無法得到每個標籤的屬性。

有人能告訴我我做錯了什麼/需要做什麼?

感謝

回答

1

當你包括findOne裏面調用相關的模型,您需要訪問相關記錄之前JSONify結果:

classification = classification.toJSON() 

那麼你應該能夠訪問包含的標籤項如你所料。

請參閱https://docs.strongloop.com/display/public/LB/Include+filter,特別是「訪問包含對象」部分。

注意,當您在數組中檢索到多個結果時,這不起作用。在這種情況下,您需要對陣列中的每個項目執行toJSON()

+0

正是我失蹤的!感謝Brian! – Jason