Languages

JavaScript - merge array of objects by property value using Lodash library

0 points
Asked by:
Maison-Humphries
821

How can I merge two arrays of objects using lodash?

For example, I have arrays of objects containing two properties such as type and value:

// ONLINE-RUNNER:browser;

var array = [
    { type: 'A', value: '1' },
    { type: 'B', value: '2' },
];

var update = [
    { type: 'A', value: '3' },
    { type: 'C', value: '4' },
];

and I want to compare and merge them by the type field, so that the result would be like this:

var retult = [
  { type: 'A', value: '3' }, // updated value
  { type: 'B', value: '2' }, // unchanged value
  { type: 'C', value: '4' }  // added value
]

How can I do that?

1 answer
0 points
Answered by:
Maison-Humphries
821

Use _.unionBy() method.

From the documentation:

This method is like _.union except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which uniqueness is computed. Result values are chosen from the first array in which the value occurs.

Practical examples

1. This example uses lodash cdn to import the library.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>
<body>
  <script>

    var array = [
        { type: 'A', value: '1' },
        { type: 'B', value: '2' },
    ];

    var update = [
        { type: 'A', value: '3' },
        { type: 'C', value: '4' },
    ];

    var result = _.unionBy(update, array, 'type');

    console.log(JSON.stringify(result, null, 4));

  </script>
</body>
</html>

2. Node.js solution:

var _ = require('lodash');

var array = [
    { type: 'A', value: '1' },
    { type: 'B', value: '2' },
];

var update = [
    { type: 'A', value: '3' },
    { type: 'C', value: '4' },
];

var result = _.unionBy(update, array, 'type');

console.log(result);

 

References

  1. lodash - npm
  2. lodash.js - Libraries - cdnjs
  3. _.unionBy() - Lodash documentation
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join