Problem Encountered with Lodash's _.merge Function

_ = require('lodash');

var firstArray = [
  {
    'name': 'MyGroup',
    'description': null,
    'items': [
      {
        '_id': 'uStqrALmwWCdyzBnc',
        'type': 'endpoints'
      },
      {
        '_id': 'tpCSiT65R5PHmQ2yn',
        'type': 'endpoints'
      }
    ],
    '_id': '8phfSHKLt9c5SB2YM'
  }
];

var secondArray= [
  {
    'name': 'MyGroup',
    'description': null,
    'items': [
      {
        '_id': 'GET_test',
        'type': 'endpoints'
      }
    ]
  }
];

console.log(JSON.stringify(_.merge(firstArray, secondArray), null, 2));

The resulting output is:

    [
  {
    "name": "MyGroup",
    "description": null,
    "items": [
      {
        "_id": "GET_test",
        "type": "endpoints"
      },
      {
        "_id": "tpCSiT65R5PHmQ2yn",
        "type": "endpoints"
      }
    ],
    "_id": "8phfSHKLt9c5SB2YM"
  }
]

When reversing the order of arrays, the merging only produces the contents of the second array. This raises questions about why the merge is partial and not complete. Is this a logical outcome or possibly a bug?

Answer №1

It makes perfect sense. The merge function simply inserts the item from the second object into the appropriate position in the array without considering your specific intentions, resulting in overwriting instead of appending or concatenating.

If you're looking to have more control over how certain cases are handled, _.mergeWith is likely what you need. This function allows you to define a custom operation for special scenarios, such as concatenating two arrays during the merge process. The documentation provides clear examples that align with the scenario you might be facing: https://lodash.com/docs#mergeWith

Answer №2

It appears that lodash is functioning according to its intended design. The software attempts to recursively combine objects, meaning that within the `items` array, the objects are meant to be merged together. This may not result in the outcome we anticipate, but it aligns with lodash's logical process.

If you encounter challenges, consider using _.mergeWith and incorporating a customizer specifically for arrays utilizing _.union:

_.mergeWith(a, b, function(objValue, srcValue) { if (_.isArray(objValue)) { return _.union(objValue, srcValue); }})

Alternatively, for better comprehension:

function customizer(objValue, srcValue) {
    if (_.isArray(objValue)) {
        return _.union(objValue, srcValue);
    }
}

_.mergeWith(a, b, customizer);

If necessary, the customizer function can be further refined to adapt to specific requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing bootstrap's switch feature with the power of AJAX

As I am still new to web application development, I kindly request some leniency in your feedback. My dilemma lies in binding the Bootstrap "switch" to a JavaScript function that triggers an AJAX request to update a database record. Below is my attempt: ...

What are the steps to modifying the material characteristics of a model loaded using OBJ + MTLLoader?

After successfully loading an .obj model along with its corresponding .mtl file to correctly map the materials onto the model, I noticed that the loaded model appears very dark. To brighten it up, I attempted to change the emissive color to white but encou ...

Optimal method for linking NodeJS and Angular in a seamless integration

I am currently working on developing a web application that integrates a Node server as the backend and Angular for the front end. At the moment, my application consists of two JavaScript files: server.js and controller.js. Below is the code snippet for ea ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...

Enhancing Your Map with Google Maps 3.54's New Style Features

I am currently working on a project using Vue2 with version 3.54 of Google Maps, which is necessary for the advancedMarkers feature. https://maps.googleapis.com/maps/api/js?key=${this.mapKey}&callback=isMapLoad&libraries=marker&v=3.54 I have g ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

Tips for displaying line breaks in a textarea and transferring data from JavaScript to the content of textarea

Seeking user input in a <textarea>, displaying it on the DOM with an edit button and preserving line breaks. When the user clicks edit, the old data is shown in a new <textarea> with breaklines. Adding an item. <form name="add" ...

Executing a keystroke in Selenium Webdriver using JavaScript

I've been writing a test using Selenium WebDriverJS, and now I need to simulate pressing a key on the keyboard. Is it possible to do this with Selenium WebDriverJS? If so, how can it be done? In Java, we achieve this as follows: driver.findElement(Lo ...

Attempting to verify the existence of a value in an SQL table prior to insertion

I have a simple table that contains an ID column and a location name column. Additionally, I have created an HTML form where users can input a new location into the table. Before adding the new location, I want to check if that location already exists in m ...

The TwilioQuest JavaScript Challenge: Unwavering Alertness

Just starting out with JavaScript and I've been learning for a couple of weeks, putting in about 8 hours so far. I know there's a similar question out there with a good answer, but I really want to understand why my approach isn't working. ...

Counting the number of documents inserted in MongoDB using Node.js

Is there a way to determine the count of inserted records without needing to repeatedly call db.collection.count()? Here's my code: exports.save = function(json) { var url = 'mongodb://localhost/apps'; MongoClient.connect(url, func ...

Save an automatically generated number into a variable and use it to reference an image file for display. This process can be accomplished using JavaScript

I'm having trouble getting my images to display randomly on a page. The images are named 0 - 9.png and I am using a pre-made function for random number generation. However, when I try to call on this function later down the page, nothing appears. It ...

"After refreshing the page, the .load() function did not run as

After loading the page and adjusting the viewport size, I am trying to retrieve the dimensions of images. While I can successfully get image dimensions after the page loads using .load, I am struggling to find a way to update the image sizes when the viewp ...

Using the window.open() function to create various windows

As we are all aware, when clicking on a submit button that contains an onClick(windown.open(...)) command, a new window is opened with the specified attributes. However, if you proceed to click on the parent window and then click on the 'submit' ...

`What's the best way to merge 3 IDs after pressing a button?`

I attempted this code <p>Watch Series Online</p> <input type="search" id="imdbseries" class="Search" name="" value="" placeholder="IMDB ID"> <input type="search" i ...

How can I refresh the positions of all items in a list using Vue-Draggable and Acts As List?

Working on my project, I have integrated a Rails API backend with the acts_as_list gem and a Vue frontend utilizing the Vue Draggable package. The drag and drop functionality is functioning as expected, with a PUT request being sent to the server. However ...

What is the most effective method for verifying a successful 200 OK response when making an Ajax call to retrieve table data?

I have a question regarding handling Ajax success responses. In previous scenarios, I returned specific data such as an ID, but now I need to return an entire table. Before retrieving this data, I want to ensure that the Ajax call was successful (status ...

Retrieving specific elements in JavaScript from a JSON file

I am attempting to extract information from a JSON file with the following data: [3000,2500,6000,2200,5000,1300]. The file is named data.txt. To achieve this, I initialize an empty array in my code. Subsequently, I utilize the $.getJSON function by passi ...

How come executing a function in the Node.js REPL using )( actually functions?

In JavaScript, why is it possible to call a function like this when tested with node.js: ~$ node > function hi() { console.log("Hello, World!"); }; undefined > hi [Function: hi] > hi() Hello, World! undefined > hi)( // Why does this work? Hell ...

When attempting to use JSON.parse on a basic object, I keep encountering an error labeled as "Unexpected token"

I'm facing an issue with the following code snippet: var a = localStorageService.get('selectedQuestionSortOrder'); $scope.selectedQuestionOrderBy = JSON.parse(a); var b = 99; Upon inspecting with a debugger, I observe the following: a - O ...