循环数据以比较值

时间:2014-06-26 14:31:40

标签: jquery

我有一个数据的对象格式为:

{
    "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个Random House条目。

所以我知道我需要通过“对象”。并检查它是否存在发布者,如果只是推送作者项目。但是,当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': []
                }]
            });
        }
    }
}

1 个答案:

答案 0 :(得分: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(在控制台中检查对象)