我有一个平面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)?
当前回答
使用对象解构
Const省略=(道具,{[道具]:_,…Rest}) => Rest; Const obj = {a: 1, b: 2, c: 3}; const objWithoutA =省略('a', obj); console.log (objWithoutA);// {b: 2, c: 3}
其他回答
嘿,当你试图复制一个对象然后删除一个属性时,你似乎遇到了引用问题。你必须在某个地方分配基本变量,这样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"}
您可以为它编写一个简单的helper函数。Lodash有一个同名的类似函数:省略
function omit(obj, omitKey) {
return Object.keys(obj).reduce((result, key) => {
if(key !== omitKey) {
result[key] = obj[key];
}
return result;
}, {});
}
omit({a: 1, b: 2, c: 3}, 'c') // {a: 1, b: 2}
另外,注意它比Object快。然后分配和删除:http://jsperf.com/omit-key
我用的是ESNext one liner
Const obj = {a: 1, b: 2, c: 3, d: 4} Const clone = (({b, c,…O}) => O)(obj) //删除b和c console.log(克隆)
这里有一个省略动态键的选项,我相信还没有提到:
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。
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"]);