2014-06-26 63 views
1

我有一個數據對象:我試圖將數據添加到相關章節通過數據循環中的格式來比較值

{ 
    "genres": [{ 
     "genreId": 1, 
     "genre": "Horror", 
     "publishers": [{ 
      "publisher": "Random House", 
      "authors": [{ 
       "author": "Stephen King", 
       "publishedYears": [2010, 2011] 
      }] 
     }, { 
      "publisher": "Penguin", 
      "authors": [{ 
       "author": "William Shakespeare", 
       "publishedYears": [2004, 2006] 
      }] 
     }] 
    }] 
} 

,所以從下拉我可以選擇一個出版商或作者。
所以我選擇蘭登書屋,然後一個「簡·史密斯」,我想給她添加到蘭登書屋部分,所以它看起來像:

{ 
     "publisher": "Random House", 
     "authors": [{ 
      "author": "Stephen King", 
      "publishedYears": [2013, 2014], 
     }, { 
      "author": "Jane Smith", 
      "publishedYears": [2013], 
     }] 
    } 

目前我做:

$('#addAuthor').on('click', function() { 
    var obj = sender.data('obj'); 
    var publisher = $('#pubdropdown').val(); 
    var author = $('#authordropdown').val(); 
    var newObj = []; 
    newObj.push({ 
     'publisher': publisher, 
     'authors': [{ 
      'author': author, 
      'publishedYears': [] 
     }] 
    }); 
}) 

但每次只是增加另一個條目,所以我最終有2個蘭登書屋條目。

所以我知道我需要通過'obj'並檢查它是否存在發佈者,如果它只是推送作者的項目。然而,如何在newObj不存在之前檢查obj對newObj的值,直到它已被推送?

我已經試過類似:

for (i = 0; i < data.genres.length; i++) { 
    for (j = 0; j < data.genres[i].publishers.length; j++) { 
     if (data.genres[i].publishers[j].publisher == newObj.publisher) { 
      //push author only 
     } else { 
      newObj.push({ 
       'publisher': publisher, 
       'authors': [{ 
        'author': author, 
        'publishedYears': [] 
       }] 
      }); 
     } 
    } 
} 
+0

廣東話你只是覈對你的newObj內設置出版商變量?你必須知道你正在尋找的出版商? – PizzaTheHut

回答

2
for (i = 0; i < data.genres.length; i++) { 
    for (j = 0; j < data.genres[i].publishers.length; j++) { 
     if (data.genres[i].publishers[j].publisher === newObj[0].publisher) { 
      data.genres[i].publishers[j].authors.push({ 
       'author': newObj[0].authors[0].author, 
       'publishedYears': [] 
      }); 
     } else { 
      data.genres[i].publishers.push(newObj[0]); 
     } 
     break; 
    } 
} 

JSFiddle(檢查控制檯對象)