我有一个平面JS对象:

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

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

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

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


当前回答

也许是这样的:

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

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

其他回答

补充一下Ilya Palkin的回答:你甚至可以动态删除键:

const x = {a: 1, b: 2, c: 3, z:26};

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

console.log(objectWithoutKey(x, 'b')); // {a: 1, c: 3, z:26}
console.log(x); // {a: 1, b: 2, c: 3, z:26};

演示在巴别塔REPL

来源:

https://twitter.com/ydkjs/status/699845396084846592

我以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

使用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 };

嘿,当你试图复制一个对象然后删除一个属性时,你似乎遇到了引用问题。你必须在某个地方分配基本变量,这样javascript就会生成一个新值。

我使用的一个简单的技巧(可能很可怕)是这样的

var obj = {"key1":"value1","key2":"value2","key3":"value3"};

// assign it as a new variable for javascript to cache
var copy = JSON.stringify(obj);
// reconstitute as an object
copy = JSON.parse(copy);
// now you can safely run delete on the copy with completely new values
delete copy.key2

console.log(obj)
// output: {key1: "value1", key2: "value2", key3: "value3"}
console.log(copy)
// output: {key1: "value1", key3: "value3"}

这个呢? 我从来没有发现这种模式周围,但我只是试图排除一个或多个属性,而不需要创建一个额外的对象。这似乎是做的工作,但有一些副作用,我不能看到。当然不是很好读。

const postData = {
   token: 'secret-token',
   publicKey: 'public is safe',
   somethingElse: true,
};

const a = {
   ...(({token, ...rest} = postData) => (rest))(),
}

/**
a: {
   publicKey: 'public is safe',
   somethingElse: true,
}
*/