Search code examples
javascripttypescriptjavascript-objects

JavaScript rename object key based on condition


I've an array of objects:

const arr = [{
    "id": "1",
    "operation": "ADD"
  },
  {
    "id": 2,
    "idmuFlag": "Mercedes",
    "operation": "DELETE"
  },
  {
    "id": 3,
    "idm": "Toyota",
    "operation": "UPDATE",
    "idmuFlag": "Ford"
  },
  {
    "id": 4,
    "idmuFlag": "Bently",
    "operation": "DELETE"
  },
  {
    "id": 5,
    "idm": "Skoda",
    "operation": "UPDATE",
    "idmuFlag": "Mustang"
  }
]

const arr1 = arr.map(arrObj => {
  if (arrObj.operation.toLowerCase() === 'delete') {
    const obj = { ...arrObj,
      idm: arrObj.idmuFlag
    }
    delete obj.idmuFlag;
    return obj;
  }
  if (arrObj.operation.toLowerCase() === 'update') {
    const obj = { ...arrObj,
      idmNew: arrObj.idmuFlag
    }
    delete obj.idmuFlag;
    return obj;
  }
  return arrObj;
});
console.log(arr1);

I want to update the key name based on the operation string value (UPDATE/DELETE). I do not want to go through for loop, rename it. I want to do it ES6/ES7 way or using destructuring, not sure though.

So, If the operation is DELETE, rename idmuFlag => idm; UPDATE, rename idmuFlag => idmNew.

I'm assigning the value to a new key and deleting the old key. Can we rename the keys directly?


Solution

  • You can create a map (ie: object) that associates operations (delete and update in your case) to the new expected keys. If the operation of the current object is not in this map then you can return the current object as there isn't any changes to be made. Otherwise, if the operation is in the map, you can get the associated key with the operation and then return your new object with that key, using destructing to remove the idmuFlag:

    const arr = [{ "id": "1", "operation": "ADD" }, { "id": 2, "idmuFlag": "Mercedes", "operation": "DELETE" }, { "id": 3, "idm": "Toyota", "operation": "UPDATE", "idmuFlag": "Ford" }, { "id": 4, "idmuFlag": "Bently", "operation": "DELETE" }, { "id": 5, "idm": "Skoda", "operation": "UPDATE", "idmuFlag": "Mustang" } ];
    
    const operationMap = {DELETE: "idm", UPDATE: "idmNew"};
    const res = arr.map(obj => {
      const op = obj.operation;
      if (!(op in operationMap)) return obj;
      const { idmuFlag, ...rest } = obj;
      const key = operationMap[op];
      return {...rest, [key]: idmuFlag};
    });
    console.log(res);