简体   繁体   English

操纵嵌套 JSON Arrays

[英]Manipulating Nested JSON Arrays

i have bellow json array我有波纹管 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"
                     }
                   ];

and then have category array然后有类别数组

const category = ["Cars","books","Table"]

based on these two array trying to create new array which will give me each day for each product how many items sold.基于这两个数组尝试创建新数组,这将给我每天每种产品售出多少件商品。 above category must follow when creating data array.创建数据数组时必须遵循上述类别。 if the product is not sold on that day then it should insert as 0.如果该产品当天未售出,则应插入为 0。

array expecting阵列期待

var finalarray = [{
        date: '2022-01-01',
        data: [7,10,0]
    }, {
        date: '2022-01-02',
        data: [2,0,5]
    }]

bellow code written not able to contiunue forward编写的波纹管代码无法继续前进

 $.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)     
   });
  1. Collect the data by date and associate each count by product按日期收集数据并按产品关联每个计数
  2. Map over the entries and query each for your category Map 遍历条目并为您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM