我有一个平面JS对象:

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

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

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

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


当前回答

你可以使用lodash库来实现这个目的(如果你需要在一个项目中使用大量的数组/对象数组/对象)。

使用lodash deepclone函数你可以做:

const _obj = _.cloneDeep(obj);
delete _obj.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}

我用的是ESNext one liner

Const obj = {a: 1, b: 2, c: 3, d: 4} Const clone = (({b, c,…O}) => O)(obj) //删除b和c console.log(克隆)

我以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方法可以做到这一点。期望2个参数,对象和一个包含键的字符串数组被删除:

removeKeys(object: { [key: string]: any }, keys: string[]): { [key: string]: any } {
  const ret: { [key: string]: any } = {};

  for (const key in object) {
    if (!keys.includes(key)) {
      ret[key] = object[key];
    }
  }

  return ret;
}