merge-strategies

Object merging made simple

Usage no npm install needed!

<script type="module">
  import mergeStrategies from 'https://cdn.skypack.dev/merge-strategies';
</script>

README

merge-strategies

Version Build Status Coverage Dependencies Vulnerabilities License Types

Object merging made simple.

Install

npm install merge-strategies

Usage

All functions return a new object -they are not mutated-, and take in objects of any type. If they receive scalars instead of Arrays or objects, data will be returned.

shallow(defaults, data)

  • If both defaults and data are objects, they will be shallow merged.
  • Keys with undefined values in a data object will acquire their value at defaults.
  • Mutations to the returned object won't have an effect over defaults.
  • Arrays won't be merged.
import { shallow } from 'merge-strategies';

// Returns: { foo: [3, 4], bar: { foo: 'foo' } }
shallow(
  { foo: [1, 2], bar: { baz: 'baz' },
  { foo: [3, 4], bar: { foo: 'foo' },
);

merge(defaults, data)

  • If both defaults and data are objects, they will be deep merged.
  • Keys with undefined values in a data object will acquire their value at defaults.
  • Mutations to the returned object won't have an effect over defaults.
  • Arrays won't be merged.
import { merge } from 'merge-strategies';

// Returns: { foo: [3, 4], bar: { baz: 'baz', foo: 'foo' } }
merge(
  { foo: [1, 2], bar: { baz: 'baz' },
  { foo: [3, 4], bar: { foo: 'foo' },
);

deep(defaults, data)

  • If both defaults and data are objects, they will be deep merged.
  • Keys with undefined values in a data object will acquire their value at defaults.
  • Mutations to the returned object won't have an effect over defaults.
  • Arrays will be concatenated.
import { deep } from 'merge-strategies';

// Returns: { foo: [1, 2, 3, 4], bar: { baz: 'baz', foo: 'foo' } }
deep(
  { foo: [1, 2], bar: { baz: 'baz' },
  { foo: [3, 4], bar: { foo: 'foo' },
);