How to use a mapping object to replace values in a data array of objects

The requirement was to show abbreviated values for the shipping item label values sourced from the NetSuite side in a React JS web application. For this, I created a map object and stored the original names and abbreviations as key-value pairs. Used a map function to replace the values in the data object before rendering.

// Store the array in the constants module or file
const shippingItemsMap: { [key: string]: string } = {
                "Customer Pick up - National": "CUST PICKUP NATIONAL",
                "Installation - Los Angeles": "LA-Install",
                "FedEx - Standard Overnight": "FedEx-Stnd-Overnight",
                "FedEx - Priority Overnight": "FedEx-Urg-Overnight",
                "UPS - Ground": "UPS-Grnd"
            };

const dataObjectArr = response.data; //Data in array of objects form
const updatedObjArr = [];
for (let i = 0; i < dataObjectArr.length; i++) {
    const newObj = {
            ...dataObjectArr[i],
            "Ship Method": shippingItemsMap[dataObjectArr[i]["Ship Method"]] || dataObjectArr[i]["Ship Method"],
            id: i + 1; // Added a key for id
    };
    updatedObjArr.push(newObj);
}
console.log("updatedObjArr", updatedObjArr);

Please note: The code is written in Typescript

Leave a comment

Your email address will not be published. Required fields are marked *