是否有一个聪明的(即优化)方法重命名一个关键在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);

其他回答

如果你想保留迭代顺序(插入的顺序),这里有一个建议:

const renameObjectKey = (object, oldName, newName) => {

  const updatedObject = {}

  for(let key in object) {
      if (key === oldName) {
          newObject[newName] = object[key]
      } else {
          newObject[key] = object[key]
      }
  }

  object = updatedObject
}
const data = res
const lista = []
let newElement: any

if (data && data.length > 0) {

  data.forEach(element => {
      newElement = element

      Object.entries(newElement).map(([key, value]) =>
        Object.assign(newElement, {
          [key.toLowerCase()]: value
        }, delete newElement[key], delete newElement['_id'])
      )
    lista.push(newElement)
  })
}
return lista

我的方法,改编好的@Mulhoon typescript帖子,用于更改多个键:

const renameKeys = <
    TOldKey extends keyof T,
    TNewkey extends string,
    T extends Record<string, unknown>
>(
  keys:  {[ key: string]: TNewkey extends TOldKey ? never : TNewkey },
  obj: T
) => Object
    .keys(obj)
    .reduce((acc, key) => ({
        ...acc,
        ...{ [keys[key] || key]: obj[key] }
    }), {});

renameKeys({id: 'value', name: 'label'}, {id: 'toto_id', name: 'toto', age: 35});
const clone = (obj) => Object.assign({}, obj);

const renameKey = (object, key, newKey) => {

    const clonedObj = clone(object);
  
    const targetKey = clonedObj[key];
  
  
  
    delete clonedObj[key];
  
    clonedObj[newKey] = targetKey;
  
    return clonedObj;
     };

  let contact = {radiant: 11, dire: 22};





contact = renameKey(contact, 'radiant', 'aplha');

contact = renameKey(contact, 'dire', 'omega');



console.log(contact); // { aplha: 11, omega: 22 };

您可以尝试lodash _mapkeys。

Var用户= { 名称:“安德鲁”, id: 25日 报道:假 }; Var重命名= _。mapKeys(用户,函数(值,键){ 返回键+ "_" + user.id; }); console.log(重命名); < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js " > < /脚本>