JavaScript 修改数组对象的 key 值

2020-12-23 12:50:29 浏览数 (1)

原数组对象:

修改数组对象的 key 值

代码语言:javascript复制
let objArr = [
  {
    name: "Rick",
    age: 14,
  },
  {
    name: "Morty",
    age: 70,
  },
];
// 旧 key 到新 key 的映射
const keyMap = {
  name: "label",
  age: "value",
};
for (let i = 0; i < objArr.length; i  ) {
  let obj = objArr[i];
  for (let key in obj) {
    let newKey = keyMap[key];
    if (newKey) {
      obj[newKey] = obj[key];
      delete obj[key];
    }
  }
}
console.log(objArr);

修改后的输出结果

0 人点赞