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
This is definitely something you can do without jQuery.
I’d approach this in two steps…
Week
value and the values being an object with theProduct
-prefixed rest of the dataWeek
keys going back into the valuesFirst 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.