我想比较node.js中对象的数组和数组,并基于比较生成一个新的json对象。 在下面的代码中,我具有日期的“ dateList” 列表和具有json数组的结果,现在,我想比较dateList和结果,如果结果对象具有日期dateList的值,那么我们必须获取执行值,然后将其推入新数组;如果不相等,则必须推为0。
服务器代码:
var dateList = [
"2018-08-01",
"2018-07-31",
"2018-07-30",
"2018-07-29",
"2018-07-28",
"2018-07-27",
"2018-07-26"
]
var result = [{
CDate: '2018-07-31',
executions: 1
},
{
CDate: '2018-07-30',
executions: 2
},
{
CDate: '2018-07-27',
executions: 3
},
{
CDate: '2018-07-26',
executions: 2
}
];
var allList = [];
for (key in dateList) {
for (keyResult in result) {
if (dateList[key] === result[keyResult].CDate) {
var obj = {
"date": dateList[key],
"value": result[keyResult].executions
}
allList.push(obj);
break;
} else {
var obj = {
"date": dateList[key],
"value": 0
}
allList.push(obj)
break;
}
}
}
console.log(allList);
当前输出:
[{
"date": "2018-08-01",
"value": 0
},
{
"date": "2018-07-31",
"value": 1
},
{
"date": "2018-07-30",
"value": 0
},
{
"date": "2018-07-29",
"value": 0
},
{
"date": "2018-07-28",
"value": 0
},
{
"date": "2018-07-27",
"value": 0
},
{
"date": "2018-07-26",
"value": 0
}
]
预期输出:
[{
"date": "2018-08-01",
"value": 0
},
{
"date": "2018-07-31",
"value": 1
},
{
"date": "2018-07-30",
"value": 2
},
{
"date": "2018-07-29",
"value": 0
},
{
"date": "2018-07-28",
"value": 0
},
{
"date": "2018-07-27",
"value": 3
},
{
"date": "2018-07-26",
"value": 2
}
]
请帮助
答案 0 :(得分:1)
该else
分支位于内部数组内部,但是,仅当内部循环未在0-entry
中找到给定日期时才要推送result
,只有在何时才能知道循环结束(新变量found
对其进行了跟踪):
var dateList = [
"2018-08-01",
"2018-07-31",
"2018-07-30",
"2018-07-29",
"2018-07-28",
"2018-07-27",
"2018-07-26"
]
var result = [{
CDate: '2018-07-31',
executions: 1
},
{
CDate: '2018-07-30',
executions: 2
},
{
CDate: '2018-07-27',
executions: 3
},
{
CDate: '2018-07-26',
executions: 2
}
];
var allList = [];
for (key in dateList) {
var found=false;
for (keyResult in result) {
if (dateList[key] === result[keyResult].CDate) {
var obj = {
"date": dateList[key],
"value": result[keyResult].executions
}
allList.push(obj);
found=true;
break;
}// else {
}
if(!found){
var obj = {
"date": dateList[key],
"value": 0
}
allList.push(obj)
//break;
}
}
console.log(allList);
另一种方法是在开头创建一个0-entry
,然后从内部循环对其进行更新并在末尾进行推送:
var dateList = [
"2018-08-01",
"2018-07-31",
"2018-07-30",
"2018-07-29",
"2018-07-28",
"2018-07-27",
"2018-07-26"
]
var result = [{
CDate: '2018-07-31',
executions: 1
},
{
CDate: '2018-07-30',
executions: 2
},
{
CDate: '2018-07-27',
executions: 3
},
{
CDate: '2018-07-26',
executions: 2
}
];
var allList = [];
for (key in dateList) {
var obj = {
"date": dateList[key],
"value": 0
};
for (keyResult in result) {
if (dateList[key] === result[keyResult].CDate) {
obj.value=result[keyResult].executions;
break;
}
}
allList.push(obj)
}
console.log(allList)