我有一个平面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省略
let source = //{a: 1, b: 2, c: 3, ..., z:26}
let copySansProperty = _.omit(source, 'b');
// {a: 1, c: 3, ..., z:26}
其他回答
使用对象解构
Const省略=(道具,{[道具]:_,…Rest}) => Rest; Const obj = {a: 1, b: 2, c: 3}; const objWithoutA =省略('a', obj); console.log (objWithoutA);// {b: 2, c: 3}
如果使用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。它看起来很冗长,但我认为拥有一行可链接的解决方案很好。
我有一个对象:带有一些键的选项
let options = {
userDn: 'somePropertyValue',
username: 'someValue',
userSearchBase: 'someValue',
usernameAttribute: 'uid',
userPassword: 'someValue'
}
我想记录所有对象excelp userPassword属性,因为我在测试一些东西,我正在使用这段代码:
console.log(Object.keys(options).map(x => x + ': ' + (x === "userPassword" ? '---' : options[x])));
如果你想让它动态,只要做一个函数,而不是显式地放置userPassword,你可以放置你想要排除的属性的值
下面是我对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 postData = {
token: 'secret-token',
publicKey: 'public is safe',
somethingElse: true,
};
const a = {
...(({token, ...rest} = postData) => (rest))(),
}
/**
a: {
publicKey: 'public is safe',
somethingElse: true,
}
*/