javascript - JS:对象的聚合数组
问题描述
我正在处理一系列更改日志(对象)
我的数组中的每个元素都是一个项目的一个字段更改。我的数组看起来像这样
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"}]
我想将字段价格的唯一更改合并到一行中我想要的结果结果:字段=价格的更改只有一行,第一条记录的旧值,最终记录的新值(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
。
如果不存在值,则分配一个对象并更新NewValue
and 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; }
推荐阅读
- ionic3 - Angular 2 - 反应形式的密码验证
- java - Android Studio 中的 glTexImage2D 模拟器错误
- python - get_text 不适用于 div 标签
- r - 如何通过在 R 中有效地过滤和分组来对数据进行子集化
- php - 在 CQRS 应用程序中执行验证/不变量
- python - ModuleNotFoundError:没有名为“PyQt5.QtWebKit”的模块
- javascript - 在html中的div中显示文本
- javascript - java - 如何在Java Web应用程序中的页面刷新后保留选定的单选按钮
- .htaccess - 在网站上存储敏感图像的最安全方法是什么?
- javascript - 从 JSON 中调用对象的值时,为什么必须用引号和加号括起来?