javascriptnode.jsfrontendweb-frontendxsjs

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"
}];

I want it to be like this

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

I want this in javascript. can anyone help me

thanks in advance


Solution

  • Current example does not check for duplicates 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);