[英]Manipulating Nested JSON Arrays
我有波紋管 json 陣列
var rowdataarray = [
{
"products": "Cars",
"solddate" : "2022-01-01",
"noofitems" : "7"
},
{
"products": "books",
"solddate" : "2022-01-01",
"noofitems" : "10"
},
{
"products": "Cars",
"solddate" : "2022-01-02",
"noofitems" : "2"
},
{
"products": "Table",
"solddate" : "2022-01-02",
"noofitems" : "5"
}
];
然后有類別數組
const category = ["Cars","books","Table"]
基於這兩個數組嘗試創建新數組,這將給我每天每種產品售出多少件商品。 創建數據數組時必須遵循上述類別。 如果該產品當天未售出,則應插入為 0。
陣列期待
var finalarray = [{
date: '2022-01-01',
data: [7,10,0]
}, {
date: '2022-01-02',
data: [2,0,5]
}]
編寫的波紋管代碼無法繼續前進
$.when(
$.each(category , function (key, val) {
$.each(rowdataarray , function (key, x) {
if(x.products == val){
finalarray .push({
"date" : x.solddate,
"data" : [x.noofitems]
})
}
})
})
).then(function () {
console.log(test)
});
category
查詢每個條目 var rowdataarray = [{"products":"Cars","solddate":"2022-01-01","noofitems":"7"},{"products":"books","solddate":"2022-01-01","noofitems":"10"},{"products":"Cars","solddate":"2022-01-02","noofitems":"2"},{"products":"Table","solddate":"2022-01-02","noofitems":"5"}] const category = ["Cars","books","Table"] const byDate = rowdataarray.reduce((m, { solddate: d, products: p, noofitems: c }) => ({...m, [ d ]: { // the date is the top-level key...m[d], [ p ]: (m[d]?.[p]?? 0) + parseFloat(c) // add the count to any existing product count } }), {}) console.log("byDate", byDate) const finalarray = Object.entries(byDate).map(([ date, counts ]) => ({ date, data: category.map(cat => counts[cat]?? 0) })) console.info("finalarray", finalarray)
.as-console-wrapper { max-height: 100%;important; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.