遍历对象并添加在日期范围内的所有值。

huangapple go评论73阅读模式
英文:

Loop through object and add all values that are in a date range

问题

以下是翻译好的部分:

我有一个查询,为用户获取过去7天的值。这些条目可能是(2)或它们可能是(20),重要的是每个日期的值都被计算并添加。

这是数据:

[{卡路里:'1170.00',上传日期:2019-12-31T21:41:42.943Z},
{卡路里:'2188.00',上传日期:2019-12-31T21:41:56.604Z},
{卡路里:'1079.00',上传日期:2019-12-31T21:43:06.372Z},
{卡路里:'2188.00',上传日期:2019-12-31T21:42:56.577Z},
{卡路里:'445.00',上传日期:2019-12-31T21:42:45.559Z},
{卡路里:'1170.00',上传日期:2019-12-31T21:42:28.609Z},
{卡路里:'445.00',上传日期:2019-12-31T21:42:15.793Z},
{卡路里:'1079.00',上传日期:2019-12-31T21:42:05.049Z}]

现在在这个示例中,上传日期是相同的,这没关系,但它应该返回{卡路里:所有总和,上传日期:“2019-12-31”},如果这里有七天,我将需要总共七个条目。

我尝试过:

我尝试了使用Date对象和一些数组过滤的各种变化,但我没有得到我满意的结果,想从这里找到更好的方法。

需要有一个循环,比较对象中所有键的日期对象,并且如果它们相等,则添加(+=)到那一天的总值中;然后继续,如果还有更多的条目,重复此过程,考虑日期。

英文:

I have a query that is getting values for the last 7 days for a user. These entries may be (2) or they may be (20) what's important is the values for each date are calculated and added.

here is the data:

[ { calories: '1170.00', upload_date: 2019-12-31T21:41:42.943Z },
  { calories: '2188.00', upload_date: 2019-12-31T21:41:56.604Z },
  { calories: '1079.00', upload_date: 2019-12-31T21:43:06.372Z },
  { calories: '2188.00', upload_date: 2019-12-31T21:42:56.577Z },
  { calories: '445.00', upload_date: 2019-12-31T21:42:45.559Z },
  { calories: '1170.00', upload_date: 2019-12-31T21:42:28.609Z },
  { calories: '445.00', upload_date: 2019-12-31T21:42:15.793Z },
  { calories: '1079.00', upload_date: 2019-12-31T21:42:05.049Z } ]

Now in this example the upload dates are the same, that's fine but what it should return is
{calories:sum of all, upload_date:"2019-12-31"} if there were seven days here I would need this to be a total of seven entries.

What I have tried:

I have tried several variations of using Date object and some array filtering but i did not arrive at a result I was content with and wanted to get a better way of doing it from here.

there needs to be a loop, a comparison of the date object(s) of all the keys in the objects and if they're equal add (+=) to the sum value of that particular day; then continue if there are more entries and repeat until all objects values have been added taking into respect the dates.

答案1

得分: 3

你可以使用 .reduce 函数来累加数组中的每个元素,

array.reduce((acc, el) => {}, {});

其中 el 是您原始数组中的元素。

现在,通过在 .reduce 中使用的这个累加器,您可以将这个对象的键设置为日期字符串,重要的是,不包含时间。一种方法是使用 new Date().toDateString();,它会得到类似于 Fri Jan 03 2020 的日期字符串。

var reduced = array.reduce((acc, el) => {
    let newKey = new Date(el.upload_date).toDateString();
    if (acc[newKey]) {
        acc[newKey] += Number(el.calories);
    } else {
        acc[newKey] = Number(el.calories);
    }
    return acc;
}, {});

现在,您的 'reduced' 对象应该看起来像 { 'Fri Jan 03 2020': 300, 'Sat Jan 04 2020': 324 }

英文:

You can use a .reduce function to add each element of your array,

array.reduce((acc, el) => {}, {});

where el is an element of your original array.

Now with this accumulator you're using in .reduce, you can make the keys of this object be a date string that - importantly! - doesn't include the time. One way to do this is via new Date().toDateString(); which gives something like Fri Jan 03 2020

var reduced = array.reduce((acc, el) => {
    let newKey = new Date(el.upload_date).toDateString();
    if (acc[newKey]) {
        acc[newKey] += Number(el.calories);
    } else {
        acc[newKey] = Number(el.calories);
    }
    return acc;
}, {});

And now your 'reduced' object should look like {'Fri Jan 03 2020' : 300, 'Sat Jan 04 2020' : 324, }

答案2

得分: 2

以下是您要翻译的代码部分:

const input = [ { calories: '1170.00', upload_date: '2019-12-31T21:41:42.943Z' },
  { calories: '2188.00', upload_date: '2019-12-31T21:41:56.604Z' },
  { calories: '1079.00', upload_date: '2019-12-31T21:43:06.372Z' },
  { calories: '2188.00', upload_date: '2019-12-31T21:42:56.577Z' },
  { calories: '445.00', upload_date: '2019-12-31T21:42:45.559Z' },
  { calories: '1170.00', upload_date: '2019-12-31T21:42:28.609Z' },
  { calories: '445.00', upload_date: '2019-12-31T21:42:15.793Z' },
  { calories: '1079.00', upload_date: '2019-12-31T21:42:05.049Z' },
  { calories: '1079.00', upload_date: '2019-12-30T21:42:05.049Z' } // added for demo
  ]
  
const output = input.reduce((all, next) => {
  const s = new Date(next.upload_date)
  const key = `${s.getFullYear()}-${(s.getUTCMonth() + 1)}-${s.getUTCDate()}`
  const exist = all.find(v => v.upload_date === key)
  if (exist) {
    exist.calories += Number(next.calories)
  } else {
    all.push({
      calories: Number(next.calories),
      upload_date: key
    })
  }
  
  return all
  
  
}, [])  

console.log(output)

请注意,这只是代码的翻译部分,没有包括任何其他内容。

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const input = [ { calories: &#39;1170.00&#39;, upload_date: &#39;2019-12-31T21:41:42.943Z&#39; },
  { calories: &#39;2188.00&#39;, upload_date: &#39;2019-12-31T21:41:56.604Z&#39; },
  { calories: &#39;1079.00&#39;, upload_date: &#39;2019-12-31T21:43:06.372Z&#39; },
  { calories: &#39;2188.00&#39;, upload_date: &#39;2019-12-31T21:42:56.577Z&#39; },
  { calories: &#39;445.00&#39;, upload_date: &#39;2019-12-31T21:42:45.559Z&#39; },
  { calories: &#39;1170.00&#39;, upload_date: &#39;2019-12-31T21:42:28.609Z&#39; },
  { calories: &#39;445.00&#39;, upload_date: &#39;2019-12-31T21:42:15.793Z&#39; },
  { calories: &#39;1079.00&#39;, upload_date: &#39;2019-12-31T21:42:05.049Z&#39; },
  { calories: &#39;1079.00&#39;, upload_date: &#39;2019-12-30T21:42:05.049Z&#39; } // added for demo
  ]
  
const output = input.reduce((all, next) =&gt; {
  const s = new Date(next.upload_date)
  const key = `${s.getFullYear()}-${(s.getUTCMonth() + 1)}-${s.getUTCDate()}`
  const exist = all.find(v =&gt; v.upload_date === key)
  if (exist) {
    exist.calories += Number(next.calories)
  } else {
    all.push({
      calories: Number(next.calories),
      upload_date: key
    })
  }
  
  return all
  
  
}, [])  

console.log(output)

<!-- end snippet -->

答案3

得分: 1

for (let i = 7; i >= 0; i--) {
   let day = new Date(Date.now() - (86400000 * i));
   let counts = data.filter(d => sameDay(day, d.upload_date));
   let caloriesOfThisDay = 0;
   counts.forEach(count => caloriesOfThisDay += count.calories);
   let dataOfThisDay = { calories: caloriesOfThisDay, upload_date: day };
}

function sameDay(d1, d2) {
    return d1.getFullYear() === d2.getFullYear() &&
      d1.getMonth() === d2.getMonth() &&
      d1.getDate() === d2.getDate();
}
英文:
for(let i=7; i&gt;=0; i--) {
   let day = new Date(Date.now() - (86400000 * i));
   let counts = data.filter(d =&gt; sameDay(day, d.upload_date));
   let caloriesOfThisDay = 0;
   counts.forEach(count =&gt; caloriesOfThisDay += count.calories);
   let dataOfThisDay = { colories: coloriesOfThisDay, upload_date: day };
}
function sameDay(d1, d2) {
    return d1.getFullYear() === d2.getFullYear() &amp;&amp;
      d1.getMonth() === d2.getMonth() &amp;&amp;
      d1.getDate() === d2.getDate();
}

First it calculates which day it is checking and then filter if its on desame day of the day it is checking.

After that, it checks all the calories and makes the data object you need.

答案4

得分: 1

Here is the translated code part:

如果您想按特定日期求和可以像这样操作

    const test = [ { calories: '1170.00', upload_date: "2019-12-31T21:41:42.943Z" },
      { calories: '2188.00', upload_date: "2019-12-31T21:41:56.604Z" },
      { calories: '1079.00', upload_date: "2019-12-31T21:43:06.372Z" },
      { calories: '2188.00', upload_date: "2019-12-31T21:42:56.577Z" },
      { calories: '445.00', upload_date: "2019-12-31T21:42:45.559Z" },
      { calories: '1170.00', upload_date: "2019-12-31T21:42:28.609Z" },
      { calories: '445.00', upload_date: "2019-12-31T21:42:15.793Z" },
      { calories: '1079.00', upload_date: "2019-12-31T21:42:05.049Z" } ];

    const filterDataByDate = (date) => test.filter(item => {
      const uploadDate = new Date(item.upload_date);
      const formattedUploadDate = uploadDate.getFullYear() + '-' + (uploadDate.getMonth() + 1) + '-' + uploadDate.getDate();
      //console.log(date,  formattedUploadDate, date === formattedUploadDate);
      return date === formattedUploadDate;
    });

    const sumOfCalories = filterDataByDate('2019-12-31').reduce((accumulator, currentValue) => {
      return accumulator += Number(currentValue.calories);
    }, 0);

    console.log("Sum of Calories:", sumOfCalories);

Please note that I've translated the JavaScript code while keeping the code structure intact.

英文:

If you want to sum by a specific date you could do something like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const test = [ { calories: &#39;1170.00&#39;, upload_date: &quot;2019-12-31T21:41:42.943Z&quot; },
  { calories: &#39;2188.00&#39;, upload_date: &quot;2019-12-31T21:41:56.604Z&quot; },
  { calories: &#39;1079.00&#39;, upload_date: &quot;2019-12-31T21:43:06.372Z&quot; },
  { calories: &#39;2188.00&#39;, upload_date: &quot;2019-12-31T21:42:56.577Z&quot; },
  { calories: &#39;445.00&#39;, upload_date: &quot;2019-12-31T21:42:45.559Z&quot; },
  { calories: &#39;1170.00&#39;, upload_date: &quot;2019-12-31T21:42:28.609Z&quot; },
  { calories: &#39;445.00&#39;, upload_date: &quot;2019-12-31T21:42:15.793Z&quot; },
  { calories: &#39;1079.00&#39;, upload_date: &quot;2019-12-31T21:42:05.049Z&quot; } ];

const filterDataByDate = (date) =&gt; test.filter(item =&gt; {
  const uploadDate = new Date(item.upload_date);
  const formattedUploadDate = uploadDate.getFullYear() + &#39;-&#39; + (uploadDate.getMonth() + 1) + &#39;-&#39; + uploadDate.getDate();
  //console.log(date,  formattedUploadDate, date === formattedUploadDate);
  return date === formattedUploadDate;
});

const sumOfCalories = filterDataByDate(&#39;2019-12-31&#39;).reduce((accumulator, currentValue) =&gt; {
  return accumulator += Number(currentValue.calories);
}, 0);

console.log(&quot;Sum of Calories:&quot;, sumOfCalories);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月3日 23:39:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定