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

一种非优化的方式是:

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

当前回答

简单地这么做会有什么问题吗?

someObject = {...someObject, [newKey]: someObject.oldKey}
delete someObject.oldKey

如果愿意,可以将其包装在函数中:

const renameObjectKey = (object, oldKey, newKey) => {
    // if keys are the same, do nothing
    if (oldKey === newKey) return;
    // if old key doesn't exist, do nothing (alternatively, throw an error)
    if (!object.oldKey) return;
    // if new key already exists on object, do nothing (again - alternatively, throw an error)
    if (object.newKey !== undefined) return;

    object = { ...object, [newKey]: object[oldKey] };
    delete object[oldKey];

    return { ...object };
};

// in use
let myObject = {
    keyOne: 'abc',
    keyTwo: 123
};

// avoids mutating original
let renamed = renameObjectKey(myObject, 'keyTwo', 'renamedKey');

console.log(myObject, renamed);
// myObject
/* {
    "keyOne": "abc",
    "keyTwo": 123,
} */

// renamed
/* {
    "keyOne": "abc",
    "renamedKey": 123,
} */

其他回答

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

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

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

如果你不想改变你的数据,考虑这个函数…

renameProp = (oldProp, newProp, { [oldProp]: old, ...others }) => ({
  [newProp]: old,
  ...others
})

Yazeed Bzadough的详细解释 https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd


下面是一个typescript友好的版本:

// These generics are inferred, do not pass them in.
export const renameKey = <
  OldKey extends keyof T,
  NewKey extends string,
  T extends Record<string, unknown>
>(
  oldKey: OldKey,
  newKey: NewKey extends keyof T ? never : NewKey,
  userObject: T
): Record<NewKey, T[OldKey]> & Omit<T, OldKey> => {
  const { [oldKey]: value, ...common } = userObject

  return {
    ...common,
    ...({ [newKey]: value } as Record<NewKey, T[OldKey]>)
  }
}

它将防止您破坏现有的键或将其重命名为相同的东西

您可以将工作包装在一个函数中,并将其分配给Object原型。也许可以使用流畅的界面样式使多个重命名流动。

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

ECMAScript 5 Specific

我希望语法不是这么复杂,但它肯定是很好的有更多的控制。

Object.defineProperty(
    Object.prototype, 
    'renameProperty',
    {
        writable : false, // Cannot alter this property
        enumerable : false, // Will not show up in a for-in loop.
        configurable : false, // Cannot be deleted via the delete operator
        value : function (oldName, newName) {
            // Do nothing if the names are the same
            if (oldName === newName) {
                return this;
            }
            // Check for the old property name to 
            // avoid a ReferenceError in strict mode.
            if (this.hasOwnProperty(oldName)) {
                this[newName] = this[oldName];
                delete this[oldName];
            }
            return this;
        }
    }
);

我会这样做:

function renameKeys(dict, keyMap) {
  return _.reduce(dict, function(newDict, val, oldKey) {
    var newKey = keyMap[oldKey] || oldKey
    newDict[newKey] = val 
    return newDict
  }, {})
}

在寻找了很多答案后,这是我最好的解决方案:

const renameKey = (oldKey, newKey) => {
  _.reduce(obj, (newObj, value, key) => {
    newObj[oldKey === key ? newKey : key] = value
    return newObj
  }, {})
}

很明显,它没有替换原来的键,而是构造了一个新对象。 问题中的方法有效,但会改变对象的顺序,因为它将新的键-值添加到最后一个对象上。