我有两个javascript对象数组:
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
和
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
我正在尝试循环遍历fullDateRange数组,查看是否存在任何actualDateRange日期,并递增该值。但我一直在使用这段代码重复:
function outputDeltaDates(fullDateObj, responseObj) {
var dateArr = [],
valueArr = [];
$.each(fullDateObj, function(index) {
var fullDate = this;
var counter = 0
$.each(responseObj, function(index) {
var fullResponse = this;
if (fullResponse['date'] == fullDate['date']) {
valueArr.push(fullResponse['value'])
dateArr.push(fullDate['date'])
} else {
if (!dateArr.includes(fullDate['date'])) {
valueArr.push(0)
dateArr.push(fullDate['date'])
}
}
})
})
return [valueArr, dateArr]
}
答案 0 :(得分:1)
如果日期存在于另一个数组中,则递增对象值属性,只需将其循环一次,如果在actualDateRange
中找到日期,则递增值
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
fullDateRange.forEach(e => {
let act = actualDateRange.find(a => a.date === e.date);
if (act) e.value += act.value;
})
console.log(fullDateRange);

答案 1 :(得分:0)
要达到预期的结果,请将增量计数器推送到 valueArr ,即
valueArr.push(++counter)
而不是
fullResponse ['value'] (将推送actualDateRange值)
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
function outputDeltaDates(fullDateObj, responseObj) {
var dateArr = [],
valueArr = [];
$.each(fullDateObj, function(index) {
var fullDate = this;
var counter = 0
$.each(responseObj, function(index) {
var fullResponse = this;
if (fullResponse['date'] == fullDate['date']) {
valueArr.push(++counter)
dateArr.push(fullDate['date'])
} else {
if (!dateArr.includes(fullDate['date'])) {
valueArr.push(0)
dateArr.push(fullDate['date'])
}
}
})
})
return [valueArr, dateArr]
}
console.log(outputDeltaDates(fullDateRange, actualDateRange))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>