5

这就是我一直在做的事情:

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' }

有没有更清洁、更简单的方法?

4

2 回答 2

10

您可以使用解构赋值

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 属性提案)

于 2016-01-28T23:49:50.530 回答
1

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:[] }

于 2016-01-28T22:07:30.707 回答