我有一个平面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。

其他回答

你也可以使用展开运算符

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

我以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, 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。它看起来很冗长,但我认为拥有一行可链接的解决方案很好。

下面是我对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']))

我在这里使用对象解构。我已经将密码分离为变量,其余变量包含除密码之外的所有对象属性和值。注意:rest不是固定的关键字,你可以根据它来命名

const obj = {name:"john", password:"Abcds12@", id:"125455"} const{密码……Rest} = obj; console.log(休息);