我有一个平面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 };
其他回答
也许是这样的:
var copy = Object.assign({}, {a: 1, b: 2, c: 3})
delete copy.c;
这样够好吗?或者说c不能被复制?
这里有一个Typescript方法可以做到这一点。期望2个参数,对象和一个包含键的字符串数组被删除:
removeKeys(object: { [key: string]: any }, keys: string[]): { [key: string]: any } {
const ret: { [key: string]: any } = {};
for (const key in object) {
if (!keys.includes(key)) {
ret[key] = object[key];
}
}
return ret;
}
使用对象解构
Const省略=(道具,{[道具]:_,…Rest}) => Rest; Const obj = {a: 1, b: 2, c: 3}; const objWithoutA =省略('a', obj); console.log (objWithoutA);// {b: 2, c: 3}
下面是我对Typescript的看法,稍微源自@Paul的回答,并使用reduce代替。
function objectWithoutKey(object: object, keys: string[]) {
return keys.reduce((previousValue, currentValue) => {
// @ts-ignore
const {[currentValue]: undefined, ...clean} = previousValue;
return clean
}, object)
}
// usage
console.log(objectWithoutKey({a: 1, b: 2, c: 3}, ['a', 'b']))
你也可以使用展开运算符
const source = { a: 1, b: 2, c: 3, z: 26 }
const copy = { ...source, ...{ b: undefined } } // { a: 1, c: 3, z: 26 }