Typescript Merge Array of Items

51 Views Asked by At

I have this type of array in the angular 14

[
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Color",
        "oldValue": "Rainbow",
        "newValue": "Rainbow1"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Pg #",
        "oldValue": "4",
        "newValue": "44"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Status",
        "oldValue": "New",
        "newValue": "Rev"
    }
]

And i want this data to be convert as below format. basically the column values to be turned to the property name.

{
"parentItem": "WBP258R",
"childItem": "WBP258R",
"Color": "Rainbow",
"Color_newValue": "Rainbow1",
"Pg #": "4",
"Pg #"_newValue": "44",
"Status":"New",
"Status_newValue": "Rev",
}

looking for help Thanks in advance

2

There are 2 best solutions below

0
Blackfaded On

You could use Array.reduce() for this purpose.

[
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Color",
        "oldValue": "Rainbow",
        "newValue": "Rainbow1"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Pg #",
        "oldValue": "4",
        "newValue": "44"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Status",
        "oldValue": "New",
        "newValue": "Rev"
    }
].reduce((acc, val) => {
    if(!acc['parentItem']){
        acc['parentItem'] = val['parentItem'];
        acc['childItem'] = val['childItem'];
    }
    acc[val['columnName']] = val['oldValue'];
    acc[`${val['columnName']}_newValue`] = val['newValue'];
    return acc;    
}, {})
0
Selaka Nanayakkara On

const inputArray = [
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Color",
        "oldValue": "Rainbow",
        "newValue": "Rainbow1"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Pg #",
        "oldValue": "4",
        "newValue": "44"
    },
    {
        "parentItem": "WBP258R",
        "childItem": "WBP258R",
        "columnName": "Status",
        "oldValue": "New",
        "newValue": "Rev"
    }
];



function transformArray(array) {
    const result = {};

    array.forEach(item => {
        const columnName = item.columnName;
        const baseKey = columnName.replace(/\s+/g, ''); // Remove spaces for property names
        result[baseKey] = item.oldValue;
        result[`${baseKey}_newValue`] = item.newValue;
    });

    
    result.parentItem = array[0].parentItem; // Add non-column properties
    result.childItem = array[0].childItem; // Add non-column properties

    return result;
}

const outputObject = transformArray(inputArray);

console.log(outputObject);