【发布时间】:2020-10-19 11:13:34
【问题描述】:
我正在处理一系列更改日志(对象)
我的数组中的每个元素都是一个项目的一个字段更改。 我的数组是这样的
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"}]
我想将 Field Price 的唯一变化合并到一行中 我想要的结果结果: Field=Price的变化只有一行,第一条记录的OldValue,最后一条记录的NewValue(orderby 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"}]
这就是我现在拥有的;
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)
}
}
});
我尝试先分离 Field=Selling Price 的那个,然后使用仅包含 Selling Price 更改的数组,如果当前行与前一个具有相同的 ItemNo,则在每个 ItemNo 上使用 forEach,弹出上一个日志,然后推送具有当前行的 NewValue 和 CreatedDate 的新日志。 最后,我会将价格变化列表和其他变化列表合并到结果数组中
【问题讨论】:
-
你能分享你的代码吗,你试过了。
-
好吧,我做到了..
标签: javascript arrays logic