others - Javascript:將對象數據推送到特定索引中

這是JSON


let arr = [ 


 {"days":3,"count" : 10 },


 {"days":4,"count" : 12 },


 {"days":7,"count" : 14 },


 {"days":9,"count" : 20 }



]




updatedArr = [ 


 {"days":0,"count" : 0 },


 {"days":0,"count" : 0 },


 {"days":3,"count" : 10 },


 {"days":4,"count" : 12 },


 {"days":0,"count" : 0 },


 {"days":6,"count" : 34 },


]



這是我嘗試的


let arr = [{


"days": 3,


"count": 10


},


{


"days": 4,


"count": 12


},


{


"days": 7,


"count": 14


},


{


"days": 9,


"count": 20


}



]



for (let index = 0; index < 6; index++) {


const element = arr[index];



let eachObject = {}



eachObject.count = 0



if (element && element !== undefined && element.days && element.days <= 5) {



 eachObject.days = element.days


 eachObject.count = element.count



 arr.splice((element.days - 1), 0, eachObject)



} else if (element && element !== undefined && element.days > 5) {



 eachObject.days = element.days


 eachObject.count += Number.parseInt(element.count)



 arr.splice(4, 0, eachObject)


} else {


 eachObject.days = 0


 eachObject.count = 0


 arr.push(eachObject)


}



}

謝謝你。

时间:

你可以用空計數構建一個新的數據集,並使用數組中的實際值更新它們。


let array = [ 


 {"days":3,"count" : 10 },


 {"days":4,"count" : 12 },


 {"days":7,"count" : 14 },


 {"days":9,"count" : 20 }


];



result = array.reduce(


 (r, { days, count }) => {


 days = days > 5 ? 5 : days


 r[days].count += count;


 return r;


 },


 Array.from({ length: 6 }, (_, days) => ({ days, count: 0 }))


);



console.log(result);

...