Sunday, 15 March 2015

jquery - Looping through data to compare values -



jquery - Looping through data to compare values -

i have object info in format of:

{ "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] }] }] }] }

i 'm trying add together info relevant sections, drop downwards can select publisher or author. select random house , author "jane smith", want add together random house section, looks like:

{ "publisher": "random house", "authors": [{ "author": "stephen king", "publishedyears": [2013, 2014], }, { "author": "jane smith", "publishedyears": [2013], }] }

at moment i'm doing:

$('#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': [] }] }); })

but each time it's adding entry end 2 random house entries.

so know need go through 'obj' , check see if publisher exists, if force author item. how can check value of obj against newobj when newobj doesnt exist until it's been pushed?

i've tried like:

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

for (i = 0; < data.genres.length; i++) { (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 (inspect object in console)

jquery

No comments:

Post a Comment