如何合并 javascript 中相同键中的相似键值
how to merge similar key values in same keys in 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);
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);