我有一个平面JS对象:
{a: 1, b: 2, c: 3, ..., z:26}
我想克隆对象除了一个元素:
{a: 1, c: 3, ..., z:26}
最简单的方法是什么(如果可能的话,更倾向于使用es6/7)?
我有一个平面JS对象:
{a: 1, b: 2, c: 3, ..., z:26}
我想克隆对象除了一个元素:
{a: 1, c: 3, ..., z:26}
最简单的方法是什么(如果可能的话,更倾向于使用es6/7)?
当前回答
我以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
其他回答
我在这里使用对象解构。我已经将密码分离为变量,其余变量包含除密码之外的所有对象属性和值。注意:rest不是固定的关键字,你可以根据它来命名
const obj = {name:"john", password:"Abcds12@", id:"125455"} const{密码……Rest} = obj; console.log(休息);
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 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。
上述使用结构化的解决方案确实受到一个事实的影响,即你有一个使用过的变量,如果你使用它,可能会引起ESLint的抱怨。
下面是我的解决方案:
const src = { a: 1, b: 2 }
const result = Object.keys(src)
.reduce((acc, k) => k === 'b' ? acc : { ...acc, [k]: src[k] }, {})
在大多数平台上(除了IE,除非使用Babel),你还可以这样做:
const src = { a: 1, b: 2 }
const result = Object.fromEntries(
Object.entries(src).filter(k => k !== 'b'))