我从这样的服务器得到一个json响应。
{
"List": [{
"title": "New",
"type": 1,
"date": "2016-07-01"
}, {
"title": "New1",
"type": 0,
"date": "2016-07-01"
}],
"List2": [{
"type": "1",
"date": "2016-07-01"
}, {
"type": "1",
"date": "2016-07-05"
}]
}
我想使用从开始日期到结束日期开始的迭代来遍历两个数组。在其中我必须检查,如果list1或list2中有日期条目。如果是这样,我必须做一些操作。请帮我这样做。我是初学者。提前谢谢
答案 0 :(得分:0)
var data = {
"List1": [{
"title": "New",
"type": "1",
"date": "2016 - 07 - 01"
}, {
"title": "New1",
"type": "0",
"date": "2016 - 07 - 05"
}, ],
"List2": [{
"type": "1",
"date": "2016-07-01"
}, {
"type": "1",
"date": "2016-07-05"
}]
};
var list1 = data.List1;
var list2 = data.List2;
console.log("FOR List 1");
for(var i in list1){
if(list1[i].date === undefined){
console.log("No Date");
}else{
console.log(list1[i].date);
}
}
console.log("FOR List 2");
for(var i in list2){
if(list2[i].date === undefined){
console.log("No Date");
}else{
console.log(list2[i].date);
}
}
更新:
var data = {
"List1": [{
"title": "New",
"type": "1",
"date": "2016 - 07 - 01"
}, {
"title": "New1",
"type": "0",
"date": "2016 - 07 - 05"
}, ],
"List2": [{
"type": "1",
}, {
"type": "1",
}]
};
var list1 = data.List1;
var list2 = data.List2;
console.log("FOR List 1");
var isDateAvailInList1 = false;
for(var i in list1){
if(list1[i].date === undefined){
continue;
}else{
isDateAvailInList1 = true;
break;
}
}
console.log("FOR List 2");
var isDateAvailInList2 = false;
for(var i in list2){
if(list2[i].date === undefined){
continue;
}else{
isDateAvailInList2 = true;
break;
}
}
if(isDateAvailInList1==false){
console.log("No Date in list1");
//Do the operation when no date in list1
}
if(isDateAvailInList2==false){
console.log("No Date in list2");
//Do the operation when no date in list2
}
答案 1 :(得分:0)
您可以生成哈希表,然后您可以使用
轻松检查对象中是否有日期if (hash['2016-07-01']) {
// check other things ...
}
var object = { "List": [{ "title": "New", "type": 1, "date": "2016-07-01" }, { "title": "New1", "type": 0, "date": "2016-07-01" }], "List2": [{ "type": "1", "date": "2016-07-01" }, { "type": "1", "date": "2016-07-05" }] },
hash = {};
Object.keys(object).forEach(function (k) {
object[k].forEach(function (a) {
hash[a.date] = hash[a.date] || {};
hash[a.date][k] = a;
});
});
console.log(hash);