我有一个平面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)?
当前回答
使用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 };
其他回答
您可以为它编写一个简单的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
我以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
上述使用结构化的解决方案确实受到一个事实的影响,即你有一个使用过的变量,如果你使用它,可能会引起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'))
我用的是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 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'));