如何用零填充数组中的缺失月份?

时间:2018-08-21 10:18:47

标签: javascript jquery arrays

我想用零填充数组中缺少的月份。我有一个像下面的数组

returnedValue.takeRetainedValue()

现在,我想在此数组中添加dashCustomerData = [{ "req_count": 1, "revenue": 11868.19, "getMonth": "August", "count(compID)": 2 }, { "req_count": 1, "revenue": 942.82, "getMonth": "January", "count(compID)": 1 }, { "req_count": 0, "revenue": null, "getMonth": "May", "count(compID)": 0 }, { "req_count": 1, "revenue": 28367.31, "getMonth": "October", "count(compID)": 2 } ] 为0的缺失月份。我尝试通过使用months数组并遍历它来实现这一点

req_count

但是它遍历了所有月份的所有记录。我只能在一个月内加零吗?

2 个答案:

答案 0 :(得分:1)

  

我想在此数组中添加缺少的月份,其中req_count为0

您可以遍历sed,并在每次迭代中,在allmonths中找到相应的条目。如果找不到,则将dashCustomerData作为req_count的新条目推送到0

查看以下演示:

dashCustomerData

答案 1 :(得分:0)

您可以使用Array#mapObject#definePropertynull替换0的值:

data = data.map(e => e.revenue ? e : Object.defineProperty(e, 'revenue', {value: 0}));

如果e.revenue truthy ,则只需保持对象不变,否则将其revenue属性重新定义为0

演示:

let data = [{"req_count":1,"revenue":11868.19,"getMonth":"August","count(compID)":2},
{"req_count":1,"revenue":942.82,"getMonth":"January","count(compID)":1},
{"req_count":0,"revenue":null,"getMonth":"May","count(compID)":0},
{"req_count":1,"revenue":28367.31,"getMonth":"October","count(compID)":2}];

data = data.map(e => e.revenue ? e : Object.defineProperty(e, 'revenue', {value: 0}));

console.log(data);

相关问题