skip to Main Content

I have the below array

var firstjson = [
                 {
                  "Week"    : "Week 1",
                  "Product" : "Apple",
                  "Buy"     : "24",
                  "Sell"    : "20",
                  "Profit"  : "100",
                  "Lost"    : "20"
                 },
                 {
                  "Week"    : "Week 1",
                  "Product" : "Egg",
                  "Buy"     : "24",
                  "Sell"    : "20",
                  "Profit"  : "100",
                  "Lost"    : "20"
                 },
                 {
                  "Week"    : "Week 2",
                  "Product" : "Apple",
                  "Buy"     : "44",
                  "Sell"    : "10",
                  "Profit"  : "10",
                  "Lost"    : "200"
                 },
                 {
                  "Week"    : "Week 2",
                  "Product" : "Milk",
                  "Buy"     : "24",
                  "Sell"    : "20",
                  "Profit"  : "100",
                  "Lost"    : "20"
                 }
                ]

I’m trying to get out like below

var finalarray = [
                  {
                   "Week"    : "Week 1",
                   "Apple_Buy" : "24",
                   "Apple_Sell" : "20",
                   "Apple_Profit" : "100",
                   "Apple_Lost" : "20",
                   "Egg_Buy" : "24",
                   "Egg_Sell" : "20",
                   "Egg_Profit" : "100",
                   "Egg_Lost" : "20"
                  },
                  {
                   "Week"    : "Week 2",
                   "Apple_Buy" : "44",
                   "Apple_Sell" : "10",
                   "Apple_Profit" : "10",
                   "Apple_Lost" : "200",
                   "Milk_Buy" : "24",
                   "Milk_Sell" : "20",
                   "Milk_Profit" : "100",
                   "Milk_Lost" : "20"
                  },
                 ]

I tried first taking the week to an array then loop through each week and push value to new array like below

var Weeklist = [];
var dataSetarray = []
$.when(
    $.each(data, function(i,item){        
        Weeklist.push(data[i]['Week'])
    })
    ).then(function () {                      
        var uniqueWeeklist = Weeklist.filter(function(itm, i, a) {
            return i == Weeklist.indexOf(itm);
        });
        for(z = 0; z<uniqueWeeklist.length; z++){
            $.when(
                $.each(data, function(x,item){               
                    if(data[x]['ATD/ETD/RETD Week'] == uniqueWeeklist[z]){
                        dataSetarray.push({
                            "year" : uniqueWeeklist[z],
                          
                        })
                    }
                })
                ).then(function () {               
                            console.log(dataSetarray)    
                });
        }                
});

but was not able to continue after that maybe there is a shot way to loop through the first array itself and create the final array with out taking the weeks to another array?

2

Answers


  1. This is definitely something you can do without jQuery.

    I’d approach this in two steps…

    1. Collect all the data into an object with the keys being the Week value and the values being an object with the Product-prefixed rest of the data
    2. Convert that object into an array with the Week keys going back into the values
    // just your data minified
    const firstjson = [{"Week":"Week 1","Product":"Apple","Buy":"24","Sell":"20","Profit":"100","Lost":"20"},{"Week":"Week 1","Product":"Egg","Buy":"24","Sell":"20","Profit":"100","Lost":"20"},{"Week":"Week 2","Product":"Apple","Buy":"44","Sell":"10","Profit":"10","Lost":"200"},{"Week":"Week 2","Product":"Milk","Buy":"24","Sell":"20","Profit":"100","Lost":"20"}];
    
    // group
    const groupByWeek = firstjson.reduce((map, { Week, Product, ...rest }) => {
      // initialise to an object if not set
      map[Week] ??= {};
    
      // merge in data
      Object.assign(
        map[Week],
        // map each key to be Product-prefixed
        ...Object.entries(rest).map(([key, val]) => ({
          [`${Product}_${key}`]: val,
        }))
      );
    
      return map;
    }, {});
    
    // convert to array
    const finalarray = Object.entries(groupByWeek).map(([Week, data]) => ({
      Week,
      ...data,
    }));
    
    console.log(finalarray);
    .as-console-wrapper { max-height: 100% !important; }
    Login or Signup to reply.
  2. First of all.. sorry for my messy code but it should be simple enough for you to understand. Some weakness which is please make sure your week 1 has unique product such that no repeated egg, apple and milk.

    var firstjson = [
                     {
                      "Week"    : "Week 1",
                      "Product" : "Apple",
                      "Buy"     : "24",
                      "Sell"    : "20",
                      "Profit"  : "100",
                      "Lost"    : "20"
                     },
                     {
                      "Week"    : "Week 1",
                      "Product" : "Egg",
                      "Buy"     : "24",
                      "Sell"    : "20",
                      "Profit"  : "100",
                      "Lost"    : "20"
                     },
                     {
                      "Week"    : "Week 2",
                      "Product" : "Apple",
                      "Buy"     : "44",
                      "Sell"    : "10",
                      "Profit"  : "10",
                      "Lost"    : "200"
                     },
                     {
                      "Week"    : "Week 2",
                      "Product" : "Milk",
                      "Buy"     : "24",
                      "Sell"    : "20",
                      "Profit"  : "100",
                      "Lost"    : "20"
                     }
                    ]
    var finalarray = []
    var list = []
    for(i = 0; i < firstjson.length; i++){
        list.push(firstjson[i].Week);
    }
    
    var unique = [...new Set(list)]
    
    for(i = 0; i < unique.length; i++){
        tempjson = {};
        tempjson.Week = unique[i]
        for(j = 0; j < firstjson.length;j++){
            if(unique[i] == firstjson[j].Week){
                tempjson[firstjson[j].Product + "_Buy"] = firstjson[j].Buy
                tempjson[firstjson[j].Product + "_Sell"] = firstjson[j].Sell
                tempjson[firstjson[j].Product + "_Profit"] = firstjson[j].Profit
                tempjson[firstjson[j].Product + "_Lost"] = firstjson[j].Lost
            }
        }
        finalarray.push(tempjson);
    }
    console.log(finalarray)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search