Search code examples
javascriptecmascript-6babeljsecmascript-harmonyecmascript-2016

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


This is how I've been doing it:

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

Is there a cleaner, simpler way?


Solution

  • You could use a 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
    

    (with the same rest/spread properties proposal for ES7 that you were already using)