这就是我一直在做的事情:
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: [] }
//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: [] }
var {children:_, ...newProps} = props;
console.log(newProps) // { id: 1, name: 'test' }
console.log(_) // [] - as an "empty" placeholder
(与您已经在使用的 ES7 相同的 rest/spread 属性提案)
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:[] }