Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 997
Evan Hobbs Avatar asked Jan 28 '16 21:01

Evan Hobbs


1 Answers

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)

like image 185
Bergi Avatar answered Oct 27 '22 00:10

Bergi