我有一个平面JS对象:

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

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

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

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


当前回答

如果你正在处理一个巨大的变量,你不希望复制它,然后删除它,因为这将是低效的。

一个简单的带有hasOwnProperty检查的for循环应该可以工作,而且它更适合未来的需求:

for(var key in someObject) {
        if(someObject.hasOwnProperty(key) && key != 'undesiredkey') {
                copyOfObject[key] = someObject[key];
        }
}

其他回答

你也可以使用展开运算符

const source = { a: 1, b: 2, c: 3, z: 26 }
const copy = { ...source, ...{ b: undefined } } // { a: 1, c: 3, z: 26 }

如果使用typescript, delete关键字解决方案将抛出编译错误,因为它破坏了实例化的对象的契约。和ES6展开运算符解决方案(const {x,…Keys} = object)可能会抛出一个错误,这取决于你在项目上使用的检测配置,因为x变量还没有开始使用。所以我想出了这个解决方案:

const cloneObject = Object.entries(originalObject)
    .filter(entry => entry[0] !== 'keyToRemove')
    .reduce((acc, keyValueTuple) => ({ ...acc, [keyValueTuple[0]]: keyValueTuple[1] }), {});

它使用Object的组合来解决这个问题。entry方法(获取原始对象的键/值对数组)和数组方法filter和reduce。它看起来很冗长,但我认为拥有一行可链接的解决方案很好。

我以Redux减速机为例:

 const clone = { ...state };
 delete clone[action.id];
 return clone;

换句话说:

const clone = { ...originalObject } // note: original object is not altered
delete clone[unwantedKey]           // or use clone.unwantedKey or any other applicable syntax
return clone                        // the original object without the unwanted 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 x = {obj1: 1, pass: 2, obj2: 3, obj3:26};

const objectWithoutKey = (object, key) => {
  const {[key]: deletedKey, ...otherKeys} = object;
  return otherKeys;
}

console.log(objectWithoutKey(x, 'pass'));