array-objects-merge

Merge arrays of objects where object are the same based on your own defined key

Usage no npm install needed!

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

README

array-objects-merge

build state vulnerabilities coverage status dependencies status dev dependencies status license style guide style guide

Merge arrays of objects where object are the same based on your own defined key

Install

npm i -S array-objects-merge

Usage

Merge many arrays of objects only write

const arrMerge = require('array-objects-merge');

const opt = { key: 'id' };

// key equals to 'id' is by default
const merge = arrMerge(opt, source1, source2, source3, ...);

// so you can do only
const merge = arrMerge({}, source1, source2, source3, ...);

The first opts object is required, don't try to skip or array-objects-merge skip your first source

Example

Make a file and insert the next content and run:

const arrMerge = require('array-objects-merge');

const source1 = [
  { id: 1, name: 'Andrea' },
  { id: 2, name: 'Marlen' },
  { id: 3, name: 'Mare' },
  { id: 4, name: 'Elyn' },
];

const source2 = [
  { id: 1, age: 15 },
  { id: 2, age: 23 },
  { id: 3, age: 17 },
  { id: 4, age: 19 },
];

const source3 = [
  { id: 1, hobbies: ['dancing', 'movies', 'write', 'yoga'] },
  { id: 2, hobbies: ['ballet', 'dancing', 'athletics', 'running'] },
  { id: 3, hobbies: ['soccer', 'volleyball'] },
  { id: 4, hobbies: ['running', 'swimming', 'study'] },
];

// merge by id property
const merge = arrMerge({ key: 'id' }, source1, source2, source3);

console.log(merge);

output:

[
  {
    id: 1,
    name: 'Andrea',
    age: 15,
    hobbies: ['dancing', 'movies', 'write', 'yoga']
  },
  {
    id: 2,
    name: 'Marlen',
    age: 23,
    hobbies: ['ballet', 'dancing', 'athletics', 'running']
  },
  {
    id: 3,
    name: 'Mare',
    age: 17,
    hobbies: ['soccer', 'volleyball']
  },
  {
    id: 4,
    name: 'Elyn',
    age: 19,
    hobbies: ['running', 'swimming', 'study']
  },
]

License

MIT. Copyright (c)