我想用零填充数组中缺少的月份。我有一个像下面的数组
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
但是它遍历了所有月份的所有记录。我只能在一个月内加零吗?
答案 0 :(得分:1)
我想在此数组中添加缺少的月份,其中req_count为0
您可以遍历sed
,并在每次迭代中,在allmonths
中找到相应的条目。如果找不到,则将dashCustomerData
作为req_count
的新条目推送到0
。
查看以下演示:
dashCustomerData
答案 1 :(得分:0)
您可以使用Array#map
和Object#defineProperty
用null
替换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);