Home > Mobile >  Manipulating Nested JSON Arrays
Manipulating Nested JSON Arrays

Time:02-10

i have bellow json array

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.

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)     
   });

CodePudding user response:

  1. Collect the data by date and associate each count by product
  2. Map over the entries and query each for your 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; }

  • Related