[英]JS: Aggregate Array of object
我正在处理一系列更改日志(对象)
我的数组中的每个元素都是项目的一个字段更改。 我的阵列看起来像这样
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。 最后我会将价格变化列表和其他变化列表合并到结果数组中
通过创建一个按CreatedDate
排序的项目数组,您可以使用一个对象与ItemNo
和Field
进行分组。
如果 novalue 存在,则分配一个对象并更新NewValue
和CreatedDate
。
const data = [{ 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" }], result = Object.values(data.reduce((r, o) => { const key = ['ItemNo', 'Field'].map(k => o[k]); r[key] ??= { ...o }; r[key].NewValue = o.NewValue; r[key].CreatedDate = o.CreatedDate; return r; }, { })); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.