Lodash: deep copy object, but not all properties

Is there a way to copy an object with lodash, but not all properties. The only way I know is to manually copy its property by property

required, for example:

var obj = { a: 'name', b: [1,2,3], c: { z: 'surname', x: [] }, d: { y: 'surname2', w: [] } }; 

and the result will look like

 var copy_obj = { b: [1,2,3], c: { z: 'surname', x: [] } }; 

Edit: I finally decided:

 var blacklist = ['a','d']; _.cloneDeep(_.omit(obj, blacklist)); 
+5
source share
5 answers
 var blacklist = ['a','d']; _.cloneDeep(_.omit(obj, blacklist)); 
-4
source

omit serves almost this purpose:

 _.cloneDeep(_.omit(obj, blacklist)); 

Spell here: https://jsfiddle.net/c639m9L2/

+8
source

You can use the pick function:

 _.pick(obj, 'b', 'c') 
+2
source

For this you can use the second parameter JSON.stringify .

 JSON.parse(JSON.stringify(obj, ['b', 'c'])) 
+1
source

You can use the assign and select combination

 Object.assign(copy_obj, _.pick(obj, ['b', 'c'])); 

Thus, if copy_obj has other properties, you do not override them.

0
source

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


All Articles