浅拷贝对象在 ES6/ES7 中遗漏了一个或多个属性?
Shallow copy object leaving out one or more properties in ES6/ES7?
我就是这样做的:
var props = { id: 1, name: 'test', children: [] }
//copy props but leave children out
var newProps = { ...props }
delete newProps.children
console.log(newProps) // { id: 1, name: 'test' }
有没有更干净、更简单的方法?
var props = { id: 1, name: 'test', children: [] }
function clone(orig, blacklistedProps) {
var newProps = {};
Object.keys(props).forEach(function(key) {
if (!blacklistedProps || blacklistedProps.indexOf(key) == -1) {
newProps[key] = props[key];
}
});
return newProps;
}
var newProps = clone(props, ['children']);
console.log(newProps) // { id: 1, name: 'test' }
var newProps1 = clone(props);
console.log(newProps1) // { id: 1, name: 'test', children:[] }
您可以使用 destructuring assignment:
var props = { id: 1, name: 'test', children: [] }
var {children:_, ...newProps} = props;
console.log(newProps) // { id: 1, name: 'test' }
console.log(_) // [] - as an "empty" placeholder
(与您已经使用的 rest/spread properties proposal for ES7 相同)
我就是这样做的:
var props = { id: 1, name: 'test', children: [] }
//copy props but leave children out
var newProps = { ...props }
delete newProps.children
console.log(newProps) // { id: 1, name: 'test' }
有没有更干净、更简单的方法?
var props = { id: 1, name: 'test', children: [] }
function clone(orig, blacklistedProps) {
var newProps = {};
Object.keys(props).forEach(function(key) {
if (!blacklistedProps || blacklistedProps.indexOf(key) == -1) {
newProps[key] = props[key];
}
});
return newProps;
}
var newProps = clone(props, ['children']);
console.log(newProps) // { id: 1, name: 'test' }
var newProps1 = clone(props);
console.log(newProps1) // { id: 1, name: 'test', children:[] }
您可以使用 destructuring assignment:
var props = { id: 1, name: 'test', children: [] }
var {children:_, ...newProps} = props;
console.log(newProps) // { id: 1, name: 'test' }
console.log(_) // [] - as an "empty" placeholder
(与您已经使用的 rest/spread properties proposal for ES7 相同)