JavaScript根据条件重命名对象键

kknvjkwl  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(75)

我有一个对象数组:

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);

我想根据操作字符串值(UPDATE/DELETE)更新密钥名称。我不想通过**for loop**,重命名它。我想用ES6/ES 7的方式还是用解构的方式来做,虽然不确定。
所以,如果操作是DELETE,重命名为idmuFlag => idm; UPDATE,重命名为idmuFlag => idmNew
我把这个值赋给一个新的键,然后删除旧的键。我们可以直接重命名密钥吗?

8zzbczxx

8zzbczxx1#

您可以创建一个Map(即:对象),它将操作(在您的情况下是删除和更新)与新的预期键关联。如果当前对象的操作不在此Map中,则可以返回当前对象,因为没有任何更改。否则,如果操作在map中,你可以获取与操作相关联的键,然后返回带有该键的新对象,使用析构来删除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);

相关问题