浅拷贝对象在 ES6/ES7 中省略一个或多个属性

Shallow copy object leaving out one or more properties in ES6/ES7?

本文关键字:一个 属性 对象 ES6 中省 ES7 浅拷贝      更新时间:2023-09-26
这就是

我一直在做的事情:

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 相同的休息/扩展属性建议)

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