是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?

一种非优化的方式是:

o[ new_key ] = o[ old_key ];
delete o[ old_key ];

当前回答

function iterate(instance) {
  for (let child of instance.tree_down) iterate(child);

  instance.children = instance.tree_down;
  delete instance.tree_down;
}

iterate(link_hierarchy);

console.log(link_hierarchy);

其他回答

function iterate(instance) {
  for (let child of instance.tree_down) iterate(child);

  instance.children = instance.tree_down;
  delete instance.tree_down;
}

iterate(link_hierarchy);

console.log(link_hierarchy);

我只想用ES6(ES2015)的方式!

我们需要跟上时代!

const old_obj = { k1: `111`, k2: `222`, k3: `333` }; console.log(`old_obj =\n`, old_obj); // {k1: "111", k2: "222", k3: "333"} /** * @author xgqfrms * @description ES6 ...spread & Destructuring Assignment */ const { k1: kA, k2: kB, k3: kC, } = {...old_obj} console.log(`kA = ${kA},`, `kB = ${kB},`, `kC = ${kC}\n`); // kA = 111, kB = 222, kC = 333 const new_obj = Object.assign( {}, { kA, kB, kC } ); console.log(`new_obj =\n`, new_obj); // {kA: "111", kB: "222", kC: "333"}

使用对象解构和展开运算符的变体:

const old_obj = {
    k1: `111`,
    k2: `222`,
    k3: `333`
};    

// destructuring, with renaming. The variable 'rest' will hold those values not assigned to kA, kB, or kC.
const {
    k1: kA, 
    k2: kB, 
    k3: kC,
    ...rest
} = old_obj;
    

// now create a new object, with the renamed properties kA, kB, kC; 
// spread the remaining original properties in the 'rest' variable
const newObj = {kA, kB, kC, ...rest};

对于一个键,这可以很简单:

const { k1: kA, ...rest } = old_obj;
const new_obj = { kA, ...rest }

你也可能喜欢更“传统”的风格:

const { k1, ...rest } = old_obj
const new_obj = { kA: k1, ...rest}

下面是创建具有重命名键的新对象的示例。

let x = { id: "checkout", name: "git checkout", description: "checkout repository" };

let renamed = Object.entries(x).reduce((u, [n, v]) => {
  u[`__${n}`] = v;
  return u;
}, {});

如果你想保持对象的相同顺序

changeObjectKeyName(objectToChange, oldKeyName: string, newKeyName: string){
  const otherKeys = cloneDeep(objectToChange);
  delete otherKeys[oldKeyName];

  const changedKey = objectToChange[oldKeyName];
  return  {...{[newKeyName] : changedKey} , ...otherKeys};

}

使用方法:

changeObjectKeyName ( {'a' : 1}, 'a', 'A');