我有一个平面JS对象:

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

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

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

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


当前回答

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

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

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

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

其他回答

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'));

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

我有一个对象:带有一些键的选项

  let options = {       
        userDn: 'somePropertyValue',
        username: 'someValue',
        userSearchBase: 'someValue',
        usernameAttribute: 'uid',
        userPassword: 'someValue'
    }

我想记录所有对象excelp userPassword属性,因为我在测试一些东西,我正在使用这段代码:

console.log(Object.keys(options).map(x => x + ': ' + (x === "userPassword" ? '---' : options[x])));

如果你想让它动态,只要做一个函数,而不是显式地放置userPassword,你可以放置你想要排除的属性的值

我用的是ESNext one liner

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

也许是这样的:

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

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