Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to specify merge behavior of arrays #32

Closed
wants to merge 2 commits into from

Conversation

faressoft
Copy link

Sample

var deepmerge = require('deepmerge');

var target = {
  name: 'Fares',
  age: 44,
  favColors: ['red', 'blue', 'green']
};

var source = {
  name: 'Fares',
  age: 44,
  favColors: ['pink', 'yellow', 'white']
};

// Default behavior
var both = deepmerge(target, source, {
  // to specify the behavior of array merging (both, target, source)
  array: 'both'
});

// Include the arrays elements of the target
var target = deepmerge(target, source, {
  array: 'target'
});

// Include the arrays elements of the source
var source = deepmerge(target, source, {
  array: 'source'
});

console.log(JSON.stringify(both, null, 2));
console.log(JSON.stringify(target, null, 2));
console.log(JSON.stringify(source, null, 2));

Output

{
  "name": "Fares",
  "age": 44,
  "favColors": [
    "red",
    "blue",
    "green",
    "pink",
    "yellow",
    "white"
  ]
}
{
  "name": "Fares",
  "age": 44,
  "favColors": [
    "red",
    "blue",
    "green"
  ]
}
{
  "name": "Fares",
  "age": 44,
  "favColors": [
    "pink",
    "yellow",
    "white"
  ]
}

@KyleAMathews
Copy link
Collaborator

@faressoft hey! I'd love to make you a collaborator so you can merge this and other PRs and roll a new release! Please signup over at #25 and let's make this happen!

@TehShrike TehShrike changed the title Add optinal options param, with options.array to specefy the merge behavior of arrays Add ability to specify merge behavior of arrays Sep 26, 2016
@TehShrike
Copy link
Owner

Interesting. I can see why an option like this would make sense, array merging behavior is pretty subjective.

It's subjective enough that my tendency would be to allow consumers to pass in a merging function, something with a signature like

function(targetElement, sourceElement, index, targetArray, sourceArray) {
}

...and call that function for each element, using whatever value the function returned in the target.

That gives users flexibility in merging arrays, without increasing the complexity of this library's code much at all.

Anyone else have any thoughts?

@TehShrike
Copy link
Owner

Please comment on #37, another pull request with a potential solution to this issue.

@TehShrike TehShrike closed this in d34ab12 Sep 29, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants