What is the best way to merge two sets of data in JavaScript?

There are two sources from which I am retrieving data.
Once the data is fetched, I need to merge them into a single source.
Here's an example;

//data structure looks like:
//from url1
{
    "data": [
        {
            "id": 7,
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8b5b1bbb0b9bdb4f6b4b9afabb7b698aabda9aabdabf6b1b6">[email protected]</a>",
            "first_name": "Michael",
            "last_name": "Lawson"
        },
    ]
}

//from url2
{
    "data": [
        {
            "id": 8,
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0cc...">">[email protected]</a>"
            "first_name": "Lindsay",
            "last_name": "Ferguson"
        }
    ]
}

Upon merging, the desired outcome for the data:

{
    "data": [
        {
            "id": 7,
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email_...">">[email protected]</a>"
            "first_name": "Michael",
            "last_name": "Lawson"
        },
        {
            "id": 8,
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email_...">">[email protected]</a>"
            "first_name": "Lindsay",
            "last_name": "Ferguson"
        }
    ]
}

Code snippet:

 const url1 = "https://reqres.in/api/users"; 
 const url2 = "https://reqres.in/api/users?page=2";

//store the data from url1
const data1 = fetch(url1).then(result=>{
return result.data;
})

//store the data from url2
const data2 = fetch(url2).then(result=>{
return result.data;
})

I attempted using Object.assign(), however it did not yield the expected results.

const data = Object.assign(data1, data2); // only retrieves data from data1, while data2 remains missing
console.log(data); 

Answer №1

give this a try

 const url1 = "https://reqres.in/api/users"; 
     const url2 = "https://reqres.in/api/users?page=2";

    //retrieve information from url1
    async function fetchData(){

        
    let response1 = await fetch(url1);
    let response2 = await fetch(url2);

    
    if (response1.status === 200 && response2.status === 200) {
        const data1 = await response1.json();
        const data2 = await response2.json();
        // handle the received data

        const combinedData = [...data1.data, ...data2.data];  // it only retrieves data from data1, missing out on data2
        console.log(combinedData); 
    }




    }

    fetchData();

Answer №2

Here's my suggested approach:

  1. Create an array to store the URLs.

  2. Utilize async/await for a smoother process.

  3. Apply map on the array to generate a new array of promises.

  4. Wait until all promises are resolved using await.

  5. Convert JSON data into JavaScript objects.

  6. Return an object that consolidates all data properties from multiple objects into one with the help of flatMap.

const urls = ['https://reqres.in/api/users','https://reqres.in/api/users?page=2'];

// Pass in the array to the function
async function getData(urls) {

  try {

    // `map` over the array to create an array of promises
    const promises = urls.map(url => fetch(url));

    // Wait for the responses to return
    const responses = await Promise.all(promises);

    // Use `map` again to parse the JSON
    // `.json()` returns a new promise so we have to
    //  use `Promise.all` again to wait for them all to resolve
    const data = await Promise.all(responses.map(res => res.json()));

    // Finally return an object that combines the data
    // within one data property
    return { data: data.flatMap(obj => obj.data) };
  
  } catch(err) {
    return err;
  }

}

(async () => {
  console.log(await getData(urls));
})();

Answer №3

If you are attempting to combine promises that resolve to arrays, remember to await each promise and utilize the spread operator to merge their elements. In order to read and parse the response, make sure to use the json method which also returns a promise. To handle this properly, I enclosed the awaits within an async IIFE (Immediately Invoked Function Expression) because using await is not allowed in non-async functions or in the global scope.

const url1 = "https://reqres.in/api/users"; 
const url2 = "https://reqres.in/api/users?page=2";

// store promise containing data from url1
const data1 = fetch(url1)
              .then(result => result.json())
              .then(result => result.data);

// store promise containing data from url2
const data2 = fetch(url2)
              .then(result => result.json())
              .then(result => result.data);

(async () => {
  const data = [...await data1, ...await data2];
  console.log(data); 
})();

Answer №4

If you want to merge all the elements from two arrays, one way is to utilize the spread operator as shown below:

const mergedArray = [...array1, ...array2];

Alternatively, you can achieve the same result using the concat method:

const mergedArray = array1.concat(array2);

Answer №5

Your data fetching method is not yet fully optimized.

The following code will return a Response object containing details about the response received.

fetch('https://reqres.in/api/users').then(response => console.log(response))

To properly retrieve the data, you should modify your code to:

fetch('https://reqres.in/api/users').then(response => response.json()).then(data => console.log(data))

Answer №6

//Here is the data structure containing information from two different URLs:
//Data from url1
const url = {
    "data": [
                {
            "id": 7,
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="513c38323930343d7f3d3026223e3f112334202334227f383f">[email protected]</a>",
            "first_name": "Michael",
            "last_name": "Lawson"
        },
    ]
}

//Data from url2
const urlTwo = {
    "data": [
        {
            "id": 8,
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcb0b5b2b8afbda5f2bab9aebba9afb3b29caeb9adaeb9aff2b5b2">[email protected]</a>",
            "first_name": "Lindsay",
            "last_name": "Ferguson"
        }
    ]
}

let combinedData = [...url.data, ...urlTwo.data];
console.log(combinedData);

Try implementing the above code snippet.

//Here is the updated data structure with email protection in place:
//Data from url1
const url = {
    "data": [
                {
            "id": 7,
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfa2a6aca7aeaaa3e1a3aeb8bca0a18fbdaabebdaabce1a6a1">[email protected]</a>",
            "first_name": "Michael",
            "last_name": "Lawson"
        },
    ]
}

//Data from url2
const urlTwo = {
    "data": [
        {
            "id": 8,
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0bcb9beb4a3b1a9feb6b5a2b7a5a3bfbe90a2b5a1a2b5a3feb9be">[email protected]</a>",
            "first_name": "Lindsay",
            "last_name": "Ferguson"
        }
    ]
}

let combinedData = [...url.data, ...urlTwo.data];
console.log(combinedData);

If you encounter any issues, feel free to ask for assistance.

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

The PHP script encounters an Ajax request and returns a null response

My current challenge involves sending data from the browser's local storage to PHP using AJAX. When I test the API in Postman by inputting this data (POST): [ { "product-id": "32", "product-name": "Reese Stevenson&qu ...

Having difficulty invoking a JavaScript function at a global level

Currently, I am working on a nodejs application that involves mongoDB integration. In my code, I have created a function to extract specific data from MongoDB and save it in a variable called "docs". Despite multiple attempts to declare the function global ...

Steps for obtaining images using lazy loading: <img loading="lazy"

After successfully utilizing the JavaScript-executer to locate the ImageElement, I encountered an error when attempting to extract the URL for downloading the image.svg. The error message reads "NoSuchElementException." Below is a snippet of my code: ((J ...

Extrude a face in Three.js along its respective normal vector

My goal is to extrude faces from a THREE.Geometry object, and my step-by-step approach involves: - Specifying the faces to be extruded - Extracting vertices on the outer edges - Creating a THREE.Shape with these vertices - Extruding the shape using THREE.E ...

Ways to initiate authorization for location sharing in a web browser through JavaScript techniques

I am trying to implement a feature in my AngularJS tracking module where users are prompted to share their location using JavaScript, similar to how Google Maps automatically asks for permission. My goal is to prompt the user for location sharing consent ...

Imitate a hover effect

In my list, I have images and descriptions set up in the following format: <li> <img class="photography" src="PHOTO/boat.jpg" alt="Boat on sea." /> </li> <li><div id="description" class="description"> <p>BOAT</p> ...

The optional attribute feature in Angular directives

Looking for a solution: angular .module('test') .directive('multiButton', function () { return { restrict: 'E', replace: true, scope: { disabled: '@' }, template: ' ...

How can the jQuery click() method be utilized?

Currently working on a web scraping project, I have managed to gather some valuable data. However, I am now faced with the challenge of looping through multiple pages. Update: Using nodeJS for this project Knowing that there are 10 pages in total, I atte ...

Using Angular 2 routes to navigate to various applications

I'm currently developing multiple versions of my application in different languages. Utilizing AOT (ahead of time) compilations, the end result is static deployable sites organized in a structure like this: dist - index.html -- default entry file f ...

What is the process for creating a button click listener event in Kotlin or JavaScript?

While working in IntelliJ IDEA, I have created a button in my HTML file with an ID. My goal is to change the header tag to say "button clicked" using Kotlin. After searching through kotlinlang.org and other resources, I am struggling to find a simple refe ...

Error: Attempting to execute functions on a dialog before it has been properly initialized with jQuery

Whenever a user clicks on a link, my goal is to display a modal dialog with the response of a GET method fetched using AJAX. The code looks like this: HTML: <a data-rec="@Model.rec" data-seg="@Model.seg" data-det="@Model.seg" class="btn btn-default ch ...

Instructions for positioning a 3d cube within another 3d cube with the help of three.js

I'm currently working on a project involving cargo management and I am looking to create a 3D image of the packing order. I am new to using THREE.js and need assistance in rendering the objects inside the container. While I have the positions (x, y, ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Using socket.io with node.js for callback functions

Here is the code for both client and server sides: Client Side Code: socket.on('connect', function() { showSystemMessage('Connected.'); socket.emit('setuser', wm, function(data){ console.log(dat ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

Tips for integrating the AJAX response into a Sumo Select dropdown menu

I am currently using Sumoselect for my dropdowns, which can be found at . The dropdowns on my page are named as countries, state, and cities. The countries are shown in the dropdown, and based on the country selected, the corresponding state name should a ...

Dropping challenging shapes in a block-matching game similar to Tetris

I'm currently working on a game similar to Tetris, but with a twist. Instead of removing just one line when it's full, I want to remove all connected pieces at once. However, I've run into a roadblock when trying to implement the hard-drop f ...

Add the latest value to the end of the selection option

How can I append a new value at the end of an option select box, ensuring that the number continues instead of starting from 1? var n_standard = 1; function removeStandard() { var select = document.getElementById('selectBoxStandard'); for ...

Cookie-powered JavaScript timer ceases after 60 seconds

I'm having an issue with my countdown timer where it stops counting after just one minute. It seems to pause at 54:00 when I set it for 55 minutes, and at 1:00 when I set it for 2 minutes. Any suggestions on how I can resolve this and make it continue ...

What is the best way to make a CSS element move with Javascript?

Currently working on a JavaScript game where I am in need of a CSS object to replace the original JavaScript object. Specifically, I want my "sword" CSS object to move along with my player object when it is Unsheathead. All the examples I find only show wh ...