如何在 JavaScript 中将相似的键值合并到相同的键中


var array = [{
"ADJUSTMENT_TYPE": "AP0001",
"REV_TYPE": "R"
}, {
"ADJUSTMENT_TYPE": "AP0001",
"REV_TYPE": "E"
}, {
"ADJUSTMENT_TYPE": "AP0001",
"REV_TYPE": "N"
}];

我希望它是这样的

[{
"ADJUSTMENT_TYPE": "AP0001",
"REV_TYPE": "R",
"E",
"N"
}]

我想要这个在javascript中。 谁能帮我

提前致谢

当前示例不检查重复项REV_TYPE

const array = [
{ ADJUSTMENT_TYPE: 'AP0001', REV_TYPE: 'R' },
{ ADJUSTMENT_TYPE: 'AP0002', REV_TYPE: 'E' },
{ ADJUSTMENT_TYPE: 'AP0001', REV_TYPE: 'N' },
{ ADJUSTMENT_TYPE: 'AP0001', REV_TYPE: 'N' },
{ ADJUSTMENT_TYPE: 'AP0002', REV_TYPE: 'N' },
{ ADJUSTMENT_TYPE: 'AP0002', REV_TYPE: 'N' },
];
const result = array.reduce((acc, val) => {
const findType = acc.find(t => t.ADJUSTMENT_TYPE === val.ADJUSTMENT_TYPE);
if (findType) {
findType.REV_TYPE.push(val.REV_TYPE);
} else {
acc.push({ ADJUSTMENT_TYPE: val.ADJUSTMENT_TYPE, REV_TYPE: [val.REV_TYPE] });
}
return acc;
}, []);
console.log(result);

相关内容

  • 没有找到相关文章

最新更新