What is the best way to combine two nearly identical arrays/objects using underscorejs or a similar library?

In the realm of lists, there exists an old list and a new one. The mission at hand is to combine both, even in the presence of newly added key-value pairs.

var oldList = [{
  id: 1,
  name: 'Michael',
  sex: 'male',
  goodlooking: 1
}, {
  id: 2,
  name: 'John',
  sex: 'male'
}, {
  id: 3,
  name: 'Laura',
  sex: 'female'
}];

AND...

var newList = [{
  id: 1,
  name: 'Cindy',
  sex: 'female'
}, {
  id: 2,
  name: 'Herry',
  sex: 'male'
}, {
  id: 3,
  name: 'Laura',
  sex: 'female',
  goodlooking: 1
}];

The challenge now lies in merging these two lists together to harness the best of both by substituting values for matching keys. As a result, the merged list will manifest as follows:

var mergedList = [{
  id: 1,
  name: 'Cindy',
  sex: 'female',
  goodlooking: 1
}, {
  id: 2,
  name: 'Herry',
  sex: 'male'
}, {
  id: 3,
  name: 'Laura',
  sex: 'female',
  goodlooking: 1
}];

Behold the transformations unfolding before us - Michael underwent a name and gender metamorphosis, while upholding his status of being "goodlooking." John transcended into Henry, and Laura unearthed her newfound inner beauty.

Answer №1

const combinedList = _.map(previousList, function (prevElement) {
    const newElement = _.find(updatedList, {id: prevElement.id});
    return _.merge(prevElement, newElement);
});

Answer №2

Here is a solution using plain Javascript:

const oldData = [{ id: 1, name: 'Michael', gender: 'male', age: 25 }, { id: 2, name: 'John', gender: 'male' }, { id: 3, name: 'Laura', gender: 'female' }],
    newData = [{ id: 1, name: 'Cindy', gender: 'female' }, { id: 2, name: 'Harry', gender: 'male' }, { id: 3, name: 'Laura', gender: 'female', age: 22 }],
    updatedList = JSON.parse(JSON.stringify(oldData)); // create a copy

newData.forEach(function (item) {
    updatedList.some(function (data) {
        if (item.id === data.id) {
            Object.keys(item).forEach(function (key) {
                data[key] = item[key];
            });
            return true;
        }
    });
});
document.write('<pre>' + JSON.stringify(updatedList, 0, 4) + '</pre>');

Answer №3

Perhaps something along these lines?

This code snippet will replace all values in the oldList with corresponding values from the newList, and also add new values if they exist.

mergedList = [];
_.each(oldList, function(listItem, index){
    copy = listItem;
    newValues = _.findWhere(newList, {"id": listItem.id});
    _.each(newValues, function(val,key){
        copy[key] = val;
    });
    mergedList[index] = copy
});

Answer №4

Here's a similar example:

let initialLength = prevList.length,
    combinedList = [];
while(initialLength--){
    let oldData = prevList[initialLength];
        updatedKeys = Object.keys(updatedList[initialLength]);
    for (let j=0;j<updatedKeys.length;j++){
        let newKey = updatedKeys[j];
        oldData[newKey] = updatedList[initialLength][newKey]
    }

}

Answer №5

Utilize lodash's merge function directly.

var combinedArray = _.merge(existingArray, newArray);

This function recursively combines its own enumerable attributes.
https://lodash.com/docs#combine

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

Blend multiple images using Angular

Is there a way to combine multiple images in Angular? I came across some HTML5 code that seemed like it could do the trick, but unfortunately, I couldn't make it work. <canvas id="canvas"></canvas> <script type="text/javascript"> ...

Displaying and hiding the top menu when the div is scrolled

I have developed a script that is designed to display the menu in a shaking motion and hide it as you scroll down. It functions properly when scrolling within the body of the webpage, but I am facing issues when attempting to do so with a div that has an o ...

Selection auto-closing feature

I am currently working on a button that generates a dropdown menu with various categories to choose from. I would like the dropdown to automatically close when I click outside of it, similar to how a lightbox or modal popup works on a webpage. Currently, I ...

I am looking to fetch information from a different Firestore collection by looping through data using a forEach method within an onSnapshot function

I'm struggling to grasp the concept of rendering data from Firestore in my project. I've searched extensively but haven't been able to find a solution that fits my requirements. Background Information In my Firestore database, I have collec ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

To dismiss the Div, simply click on any area outside of it. Leveraging the power of SVG, D3

I need a way to hide my div by clicking outside of it. My SVG has a background and a graph with nodes on top of that. I have a special node (circle) on the graph, clicking on which makes a box appear. To show the box, I use the following code: d3.select ...

What's the best way to save data from an HTML input field into a JavaScript array?

Can someone help me with storing a value from an HTML input field into a JavaScript array after a button click, and then displaying that array data on the screen? Here is the HTML code I am currently working with: <!DOCTYPE HTML> <html> < ...

Attempting to perform recursion on two functions simultaneously may result in one of the functions being undefined

There is a page on my site that clients tend to keep open for long periods of time without refreshing, sometimes over 24 hours. Some of the actions on this page require a valid PHP session, so I created a simple set of functions to check this every 10 minu ...

Exploring methods to access specific values from an array containing multiple values using Lodash in Angular 4

Hey, I have an array that looks like this: [ 0: "Migration, MD" 1: "Lution, MD" 2: "Mover, MD" 3: "Dee" 4: "Prov10A" ] I would like to extract the values that contain the word "MD" in them. In other words, I want a result like this: [ 0: "Migratio ...

What are some ways to postpone the execution of a function in React or NextJs?

How do I automatically redirect to the home page after 5 seconds of accessing a page in NextJS? I attempted to achieve this using the following code: useEffect(() => { const timer = setTimeout(() => { redirect('/home') ...

A guide on how to retrieve POST form fields in Express

My form design is quite simple: <form id="loginformA" action="userlogin" method="post"> <div> <label for="email">Email: </label> <input type="text" id="email" name="email"></input> </div> & ...

Utilizing the power of JQuery's each() function alongside UI.sortable() for enhanced

Need help with updating data-priority attribute after sorting an unordered list using jQuery ui. Currently, the attribute is only set on load and not updated after each sort. I have created a fiddle to demonstrate the issue. It seems like a simple fix but ...

Error: React unable to locate module './WebpackMissingModule'

Recently I started diving into React, and I'm encountering some difficulties trying to export components. Here is my current index.js file setup: import React from 'react'; import ReactDOM from 'react-dom'; import SearchBar from ...

Using ES6 to generate objects within other objects

Dealing with data from a local API can be challenging, especially when you have limited control over the incoming data. However, I am looking to transform the data post my API call using a custom function. This is my current approach transformArray = () ...

Learning the art of Javascript programming within the HTML5 realm

Seeking assistance with a JavaScript project - I'm attempting to develop a Bubble Buster game reminiscent of pong, but with multiple bubbles. The goal is to have falling bubbles on screen (roughly 100 in total) in various colors dropping from random l ...

What is the best approach to identify duplicated objects within an array?

I have an array with a specific structure and I am looking to add non-duplicate objects to it. [ { applicationNumber: "2", id: "8cca5572-7dba-49de-971b-c81f77f221de", country: 23, totalPrice: 36 }, { applicationNumber: "3", id: "8cc ...

Utilizing Fragments in Vuejs 2.x with Jsx - A User's Guide

Considering the presence of Fragments in React and the lack of a specific solution in the official Vuejs GitHub thread, what alternative methods could be used in Vuejs? This information may be beneficial for developers transitioning from a React backgrou ...

The issue with the autoresize feature in the tinymce plugin arises when trying to delete HTML img content using the backspace

When using the tinymce editor with the autoresize plugin enabled, I have noticed that it works correctly with text. However, there is an issue when inserting HTML content via execCommand. For example, if I insert the following code: <div> < ...

You are unable to move the image to the top of the screen after zooming it with CSS

I implemented an image viewer component with interactive buttons for rotating, zooming in, and zooming out. Upon clicking a button, CSS transform is applied to the image. However, I encountered an issue where, when zooming the image, it cannot be scrolled ...

Changing Page Content with Ajax Post-Redirect Pattern

Just had a quick question. Can the redirected page be affected by ajax's success function? The code will provide a better explanation. $.ajax({ type: "POST", url: "/admin/done", data: { ...