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': []
}]
});
}
}
}
广东话你只是核对你的newObj内设置出版商变量?你必须知道你正在寻找的出版商? – PizzaTheHut