A small copy object that leaves one or more properties in ES6 / ES7?

Here is how I did 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?

+5
source share
2 answers

You can use the 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 suggestion of properties for adding / distributing for ES7 that you already used)

+8
source

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

Source: https://habr.com/ru/post/1241760/


All Articles