Combining two JSON datasets using specific fields in Javascript

Two JSON inputs are provided:

[
  {
    userId: 32159,
    userFirstName: "john",
    userLastName: "doe",
    plans: [ ]
  },
  {
    userId: 32157,
    userFirstName: "dave",
    userLastName: "mess",
    plans: [ ]
  }
]

and

[
      {
        userId: 32159,
        userFirstName: "john",
        userLastName: "doe",
        results: [ ]
      },
      {
        userId: 32157,
        userFirstName: "dave",
        userLastName: "mess",
        results: [ ]
      }
]

I require the following combined output:

[
      {
        userId: 32159,
        userFirstName: "john",
        userLastName: "doe",
        plans: [ ],
        results: [ ]
      },
      {
        userId: 32157,
        userFirstName: "dave",
        userLastName: "mess",
        plans: [ ],
        results: [ ]
      }
 ]

Seeking assistance to achieve this in JavaScript. The 'userId' field is unique in this case.

Answer №1

One approach to achieve object extension is by iterating through a collection, selecting the corresponding object, and extending it. Here's an example:

var array1 = [], array2 = [],
    finalArray = [];

$.each(array1, function(index1, obj1) {
    $.each(array2, function(index2, obj2) {
        if (obj1.userId === obj2.userId) {
            finalArray.push($.extend({}, obj1, obj2));
            return false;
        }
    });
});

console.log(finalArray);

Answer №2

To achieve this, you can utilize the underscore-min.js file and implement the following code snippet using its built-in functions:

 _.each(json1, function(data1) {
    _.each(json2, function(data2) {
            if (data1.userId = data2.userId) {
                _.extend(data1, data2.results);
            }
        }

    })

  });

Answer №3

If you're looking to achieve this using just JavaScript, here is one approach you can take.

function duplicate(obj1, obj2) {
    for (var key in obj1)
        if (obj1.hasOwnProperty(key))
            obj2[key] = obj1[key];
}

function combineArrays(arr1, arr2) {
    var finalArray = [];

    for (var i = 0; i < arr1.length; i++) {
        finalArray.push({});
        duplicate(arr1[i], finalArray[i]);
    }

    for (var j = 0; j < arr2.length; j++)
        duplicate(arr2[j], finalArray[j]);

    return finalArray;
}

combineArrays(yourfirstarray, yoursecondarray);

Answer №4

The concept you're looking for is known as Concurrent Processing in Functional Programming. You have two sets of data that need to be processed simultaneously in order to achieve a desired result. The code snippet provided below demonstrates this process:

http://repl.it/Ll1/1

// Array Array -> Array
// Assume that the length of array A is equal to the length of array B
// and the items are sorted correctly to align their records
function zip(a, b) {
    // Object Object -> Object
    function combineResults(itemA, itemB) {
        itemA["results"] = itemB["results"];
        return itemA;
    }
    
    if (a.length === 0) {
        return [];
    } else {
        return [combineResults(a[0], b[0])].concat(zip(a.slice(1), b.slice(1)));
    }
}

zip(a, b);

Answer №5

To streamline the process, I suggest breaking down the tasks into specific functions:

function mergeObjects(firstObj, secondObj) {
  if (firstObj && secondObj) { for (var key in secondObj) { firstObj[key] = secondObj[key]; } }
  return firstObj;
}

function mergeAndSortArrays(arr1, arr2) {
    return arr1
        .concat(arr2)
        .sort(function (a, b) { return a.userId - b.userId; });
}

function combineArrays(arr1, arr2) {
    var mergedArr = mergeAndSortArrays(arr1, arr2);
    for (var i = 0, len = mergedArr.length - 1; i < len; i++) {
        if (mergedArr[i].userId === mergedArr[i+1].userId) {
            mergedArr[i] = mergeObjects(mergedArr[i], mergedArr[i+1]);
            mergedArr.splice(i+1, 1);
            i--; len--;
        }
    }
    return mergedArr;
}

combineArrays(arr1, arr2);

Answer №6

Utilizing jQuery's extend method:

var data1 = [{
    id: 32159,
    firstName: "alice",
    lastName: "smith",
    info: []
}, {
    id: 32157,
    firstName: "bob",
    lastName: "jones",
    info: []
}];

var data2 = [{
    id: 32157,
    firstName: "bob",
    lastName: "jones",
    details: []
}, {
    id: 32159,
    firstName: "alice",
    lastName: "smith",
    details: []
}];

var mergedData = [];

for (i = 0; i < data1.length; i++) {
    for (j = 0; j < data2.length; j++) {
        if (data1[i].id == data2[j].id) 
            mergedData.push($.extend(data1[i], data2[j]));
    }
}

console.log(mergedData);

Fiddle here

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

Activate an event on a separate webpage using jQuery or JavaScript

Currently, I am in the process of working on a project with 2 distinct pages: Index Settings On the Settings page, I have implemented a button to close an element and hide it. However, I am encountering an issue where I want the elements on the Index pa ...

The Vue component does not render the JS Promise and instead displays it as

After setting up a promise that will be returned once a correct event is called with the correct action, I have the following code: import {EventBus} from "./EventBus"; export function completed() { EventBus.$on('queue-action', e => { ...

Having trouble receiving response from retrofit v2 call

Currently in the process of upgrading retrofit from version 1.9 to v2.1.0. I am trying to manually convert the response json but encountering an unexpected output: log res retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall@41acd528-okhttp3.Response ...

Using AJAX and jQuery for database connectivity allows for seamless data retrieval and manipulation

Greetings! I am currently facing an issue with AJAX & JQUERY while trying to access my database. After researching online, I found a script that seemed promising for my problem. However, when I attempted to implement it, I encountered difficulties. Using ...

What is the best way to create a timer using JavaScript?

I'm looking for a reverse timer to track session timeout. I found a code on codepen that works as a clockwise timer, but my attempts to make it counterclockwise have failed. Can someone please suggest a solution? I want the timeout to be either 1 hour ...

Django not receiving data from AJAX GET request

I am attempting to transmit data stored in localStorage through an AJAX GET request to Django, but the Django server does not seem to receive it. I have verified that there is data in localStorage("preselection") as indicated by the output of console.log. ...

Jackson Mixin: for deserializing route identifiers

I have implemented the Jackson Mixin for deserializing a mongo object and this is how my Mixin looks: public interface MyMixin { /** * Mixin to set key value for pojo. * @param key key * @param value value */ @JsonAnySetter void put(Stri ...

Setting an interval for a specific function to trigger after a delay of 5 seconds

I'm struggling with setting an interval for the $.get ajax method in my code. Take a look at what I have so far... setInterval(function () { passFunction(jsonData); } ,5); $.get({ url: 'pass.php', success: ...

What is the best way to respond to a hashchange event within AngularJs?

I am new to AngularJs and I am trying to update the page on hashchange events. Currently, I have this code which I know is not the proper way to do it: <!DOCTYPE html> <html> <head> <style> #hashdrop { display:block; ...

Typescript: Determine when a property should be included depending on the value of another property

Having some difficulty with Typescript and React. Specifically, I am trying to enforce a type requirement for the interface Car where the property colorId is only required if the carColor is set to 'blue'. Otherwise, it should not be included in ...

Cannot instantiate Marker Clusterer as a constructor

I am facing an issue with implementing Marker Clusterer in my app. I have successfully installed '@google/markerclusterer' in my project and imported it as shown below. However, a puzzling error keeps popping up: core.js:4002 ERROR TypeError: _go ...

Obtain information about a div element while scrolling

Looking to enhance my social feed page by adding a view count feature for each post. The challenge is figuring out how to keep track of views as the user scrolls down the page. Any suggestions? ...

React Material-UI Table Cell departure event

I have a material UI table with editable fields within the rows. There are various events such as onInputCapture, onFocusCapture, and others. However, I am having trouble finding an event that should be triggered when I leave the cell or finish editing. ...

Is it secure to store information that impacts component rendering within a JWT payload?

I am currently developing a MERN app where users have various roles, and different components are rendered based on their role in React. In my application, I store a JWT containing the user's ID and role in a cookie, which is then decoded in a global ...

What is the best way to implement a gradual decrease in padding as the viewport resizes using JavaScript

My goal is to create a responsive design where the padding-left of my box gradually decreases as the website width changes. I want the decrease in padding to stop once it reaches 0. For instance, if the screen size changes by 1px, then the padding-left sh ...

Use ajax to add rows to the second-to-last table

I am facing a situation where I have a table with 25 default rows. When scrolling to the bottom of the table, I want to dynamically insert another set of 25 rows. Everything is functioning correctly, but in a specific scenario, I need to preserve the last ...

Replacements of JSON null values within Mantle

Utilizing Mantle for parsing JSON data, the typical structure includes: "fields": { "foobar": 41 } However, there are instances where the value of foobar is null: "fields": { "foobar": null } This leads to an exception being thrown ...

Prevent the Stop Button from triggering submission and then utilize JavaScript to submit the form

I have a global delete button utilized in various sections of my site. Below is the code snippet for reference. public function delete_button($id_to_be_deleted, $form_to_post_to, $button_name){ return form_open($form_to_post_to, array('class&apos ...

Invoking WinJS.Binding.List.createFiltered with an asynchronous call to the predicate function

Is there a way to wait for the async operation in this code snippet and use its result as the predicate instead of always returning false? return someList.createFiltered(function(item) { var filter = false; var ...

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...