我有一个平面JS对象:

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

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

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

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


当前回答

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

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

其他回答

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

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

或者如果你接受属性为未定义:

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

JavaScript中有一个析构赋值语法可以使用

let obj = {a: 1, b: 2, c: 3, z:26};
let {b, ...rest} = obj;

// skips the "Unused variable" warning
let {b: _, ...rest} = obj;

// removes property based on the dynamic key
const dynamicKey = "b";
let {[dynamicKey]: _, ...rest} = obj;

现代浏览器已经开箱即用地支持它。 参见:JavaScript操作符:解构赋值:对象中的Rest

对于旧的浏览器版本,有一个选项可以使用Babel来支持解构赋值。它将被翻译成:

"use strict";

function _objectWithoutProperties(obj, keys) {
  var target = {};
  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }
  return target;
}

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

var y = _objectWithoutProperties(x, ["b"]);

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

你也可以使用展开运算符

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