Lodash - Difference between extend/assign, merge and defaults functions
For whatever reasons, my brain refuses to remember the behaviors of the aforementionned utility functions to deal with objects fusion. According to this stackoverflow issue, it seems that I'm not the only one, so I hope this cheatsheet would be useful to someone else.
Function aliases
The _.assign
naming convention is favored over _.extend
to be in sync with ES6
Comparison
n = 'name', w = 'weapons' | Assign | Merge | Defaults |
---|---|---|---|
{n: 'Asterix'} {n: 'Obelix'} |
{n: 'Obelix'} | {n: 'Obelix'} | {n: 'Asterix'} |
{n: 'Asterix', w: 'glaive'} {n: 'Obelix'} |
{n: 'Obelix', w: 'glaive'} | {n: 'Obelix', w: 'glaive'} | {n: 'Asterix', w: 'glaive'} |
{n: 'Asterix', ws: ['glaive', 'potion']} {n: 'Obelix', ws: ['menhir']} |
{n: 'Obelix', ws: ['menhir']} | {n: 'Obelix', ws: ['menhir', 'potion']} | {n: 'Asterix', ws: ['glaive', 'potion']} |
{n: 'Asterix', ws: ['glaive', 'potion']} {n: 'Obelix', ws: ['menhir']} |
{n: 'Obelix', ws: ['menhir']} | {n: 'Obelix', ws: ['menhir', 'potion']} | {n: 'Asterix', ws: ['glaive', 'potion']} |
{n: 'Asterix', ws: ['glaive', 'potion']} {n: 'Obelix', ws: ['menhir']} {n: 'Idefix', ws:['claws']} |
{n: 'Idefix', ws: ['claws']} | {n: 'Idefix', ws: ['claws', 'potion']} | {n: 'Asterix', ws: ['glaive', 'potion']} |
Cascade order
_.defaults(result, projectConf, userConf, systemConf)