我有一个平面JS对象:

{a: 1, b: 2, c: 3, ..., z:26}

我想克隆对象除了一个元素:

{a: 1, c: 3, ..., z:26}

最简单的方法是什么(如果可能的话,更倾向于使用es6/7)?


当前回答

这里有一个省略动态键的选项,我相信还没有提到:

const obj = { 1: 1, 2: 2, 3: 3, 4: 4 };
const removeMe = 1;

const { [removeMe]: removedKey, ...newObj } = obj;

removeMe别名为removedKey并被忽略。newObj变成{2,2,3,3,4,4}。注意,删除的键不存在,值不只是设置为undefined。

其他回答

也许是这样的:

var copy = Object.assign({}, {a: 1, b: 2, c: 3})
delete copy.c;

这样够好吗?或者说c不能被复制?

使用lodash清洁和快速,有了这个解决方案,您可以删除多个键,也不改变原始对象。这在不同的情况下具有更强的可扩展性和可用性:

import * as _ from 'lodash';

function cloneAndRemove(
    removeTheseKeys: string[],
    cloneObject: any,
): object | never {
    const temp = _.cloneDeep(cloneObject);
    removeTheseKeys.forEach((key) => {
        delete temp[key];
    });

    return temp;
}

export { cloneAndRemove };

您可以为它编写一个简单的helper函数。Lodash有一个同名的类似函数:省略

function omit(obj, omitKey) {
  return Object.keys(obj).reduce((result, key) => {
    if(key !== omitKey) {
       result[key] = obj[key];
    }
    return result;
  }, {});
}

omit({a: 1, b: 2, c: 3}, 'c')  // {a: 1, b: 2}

另外,注意它比Object快。然后分配和删除:http://jsperf.com/omit-key

下面是我对Typescript的看法,稍微源自@Paul的回答,并使用reduce代替。

function objectWithoutKey(object: object, keys: string[]) {
    return keys.reduce((previousValue, currentValue) => {
        // @ts-ignore
        const {[currentValue]: undefined, ...clean} = previousValue;
        return clean
    }, object)
}

// usage
console.log(objectWithoutKey({a: 1, b: 2, c: 3}, ['a', 'b']))

使用对象解构

Const省略=(道具,{[道具]:_,…Rest}) => Rest; Const obj = {a: 1, b: 2, c: 3}; const objWithoutA =省略('a', obj); console.log (objWithoutA);// {b: 2, c: 3}