我有一个平面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 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'));
使用对象解构
Const省略=(道具,{[道具]:_,…Rest}) => Rest; Const obj = {a: 1, b: 2, c: 3}; const objWithoutA =省略('a', obj); console.log (objWithoutA);// {b: 2, c: 3}
您可以为它编写一个简单的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
我有一个对象:带有一些键的选项
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,你可以放置你想要排除的属性的值
var clone = Object.assign({}, {a: 1, b: 2, c: 3});
delete clone.b;
或者如果你接受属性为未定义:
var clone = Object.assign({}, {a: 1, b: 2, c: 3}, {b: undefined});