浅拷贝对象遗漏ES6 / ES7中的一个或多个属性?

时间:2016-01-28 21:56:36

标签: javascript ecmascript-6 babeljs ecmascript-harmony ecmascript-7

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



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




是否有更简洁的方式?

2 个答案:

答案 0 :(得分:9)

您可以使用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相同)

答案 1 :(得分: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:[] }