In my current project, I am handling an array of change logs, each representing a field change in an item.
Here is how my changeLogArray appears:
changeLogArray=[{"ItemNo":"01", "Field":"Price","OldValue":"100","NewValue":"200","CreatedDate":"17/10/2020"},
{"ItemNo":"01", "Field":"Price","OldValue":"200","NewValue":"300","CreatedDate":"18/10/2020"},
{"ItemNo":"01", "Field":"Price","OldValue":"300","NewValue":"400","CreatedDate":"19/10/2020"},
{"ItemNo":"01", "Field":"Name","OldValue":"A","NewValue":"B","CreatedDate":"19/10/2020"}]
I aim to consolidate the changes in the Price field into a single row with the OldValue from the first record and NewValue from the last record (ordered by CreatedDate).
[{"ItemNo":"01", "Field":"Price","OldValue":"100","NewValue":"400","CreatedDate":"19/10/2020"},
{"ItemNo":"01", "Field":"Name","OldValue":"A","NewValue":"B","CreatedDate":"19/10/2020"}]
The approach I have taken so far involves filtering out records where Field is not 'Selling Price', creating separate arrays for Selling Price changes and other changes, and then processing these arrays to achieve the desired result.
var lstToDisplayNotSellingPrice = changeLogArray.filter(item => {
return item.Field != 'Selling Price'
})
var lstToDisplaySellingPrice = changeLogArray.filter(item => {
return item.Field == 'Selling Price'
})
var resultChangeLogSellingPrice = []
changeLogArray.forEach((item, index) =>{
var distinctItemIndex
if(index == 0 || item.ItemNo != lstToDisplaySellingPrice[index-1].ItemNo){
resultChangeLogSellingPrice.push(item)
distinctItemIndex = index
}else{
if(item.FieldLevel == lstToDisplaySellingPrice[index-1].ItemNo){
resultChangeLogSellingPrice.pop()
var itemLog = lstToDisplaySellingPrice[index-1]
itemLog.NewValue = item.NewValue
itemLog.CreatedDate = item.CreatedDate
resultChangeLogSellingPrice.push(itemLog)
}
}
});
I followed this method to segregate Selling Price changes, update the necessary logs, and then combine both sets of changes into the final result array.