Combining arrays of objects sharing a common key yet varying in structure

Currently, I am facing a challenge while working on this problem using Typescript. It has been quite some time since I started working on it and I am hoping that the helpful community at StackOverflow could provide assistance :)

The scenario involves two array structures:

var localUsers = [{
    firstName: "Joe", 
    lastName: "Bloggs", 
    id: "44c021ab-be92-409b-99ad-4c3fe61d894a"
}, {
    firstName: "Pete", 
    lastName: "Doe", 
    id: "017b4dab-d58b-475e-ab31-6363d9de25c0"
}, {
    firstName: "Andy", 
    lastName: "NotRemote", 
    id: "2233e4cb-d324-463d-9a42-24b1b4cd3e11"
}]

//The above array is used for a database lookup

var remoteUsers = [{ 
    id: "44c021ab-be92-409b-99ad-4c3fe61d894a",
    timestamp: "2017-07-01T12:00:00.000"
}, {
    id: "017b4dab-d58b-475e-ab31-6363d9de25c0",
    timestamp: "2017-07-01T13:30:00.000"
}]

I am looking to merge these arrays based on the id key. All keys in remoteUsers will have a matching entry in localUsers, but the reverse may not always be true. The desired output should resemble the following:

var allUsers = [{
    firstName: "Joe", 
    lastName: "Bloggs", 
    id: "44c021ab-be92-409b-99ad-4c3fe61d894a",
    timestamp: "2017-07-01T12:00:00.000"
}, {
    firstName: "Pete", 
    lastName: "Doe", 
    id: "017b4dab-d58b-475e-ab31-6363d9de25c0",
    timestamp: "2017-07-01T13:30:00.000"
}, {
    firstName: "Andy", 
    lastName: "NotRemote", 
    id: "2233e4cb-d324-463d-9a42-24b1b4cd3e11",
    timestamp: null
}]

At the moment, I do not have access to libraries like underscore or lodash.

Thank you kindly for your assistance!

Answer №1

Combine them using the map method

let localUsers = [{ firstName: "Joe", lastName: "Bloggs", id: "44c021ab-be92-409b-99ad-4c3fe61d894a" }, { firstName: "Pete", lastName: "Doe", id: "017b4dab-d58b-475e-ab31-6363d9de25c0" }, { firstName: "Andy", lastName: "NotRemote", id: "2233e4cb-d324-463d-9a42-24b1b4cd3e11" }]
let remoteUsers = [{ id: "44c021ab-be92-409b-99ad-4c3fe61d894a", timestamp: "2017-07-01T12:00:00.000" }, { id: "017b4dab-d58b-475e-ab31-6363d9de25c0", timestamp: "2017-07-01T13:30:00.000" }]

localUsers = localUsers.map(item => Object.assign(item, {timestamp: remoteUsers.find(user => user.id == item.id)?.timestamp}))
console.log(localUsers)

Answer №2

I quickly put together this function, it's not optimized but gets the job done. Hopefully, this is useful. Saeed's answer seems to be more refined.

function findUserByID(id, userList) {
    var index;
    for (index = 0; index < userList.length; index++) {
        if (userList[index].id === id) {
            return userList[index];
        }
    }

    return false;
}

function combineUsers(localUsers, remoteUsers){
    var combinedList = []
    for (const user of localUsers) {
        var foundUser = findUserByID(user.id, remoteUsers);
        
        combinedList.push({
            firstName: user.firstName,
            lastName: user.lastName,
            id: user.id,
            timestamp: foundUser.id || null
        });
    }
    return combinedList;
}

Answer №3

One potential solution is to:

const localData = [{ name: "Alice", age: 30, id: "12345678" }, { name: "Bob", age: 25, id: "87654321" }]
const remoteData = [{ id: "12345678", date: "2022-01-01T12:00:00.000" }, { id: "87654321", date: "2022-01-02T13:30:00.000" }]


const removeDataObject = remoteData.reduce((accumulator, current) => (accumulator[current.id] = current, accumulator), {})
const updatedData = localData.map(item => ({ 
  ...item,
  date: null,
  ...removeDataObject[item.id],
}))

console.log(updatedData)

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

Issues with the functionality of the jQuery notify plugin are being encountered when used in a

I am currently utilizing the jQuery notify plugin and have included all the necessary JS files in the header. However, whenever I attempt to call the $.notify function in another JS file that also involves AJAX, I encounter difficulty accessing the $.notif ...

Can text be inserted into an SWF file using ASP.NET or Javascript via an online platform?

I am managing a website that features videos created by a graphic designer who updates and adds new content regularly. I am looking to add dynamic text to these videos after a specific amount of time, such as "Hosted by XXX". However, I am hesitant to ask ...

Ag-Grid: Matching colors with filtering functionality

Can AG-Grid be configured to highlight matching cells during quick filtering? For example, if I have the following data: [ { firstName: 'Tom', lastName: 'Doe', company: 'Tesla' }, { firstName: 'Tim', lastName: & ...

What are the steps for executing an API and entering data into it?

I have developed an API using NodeJS, ExpressJS and MongoDB to filter and sort school data based on location and fees. The main code snippet looks like this: const express = require('express'); const bodyparser = require('body-parser') ...

The error message "Uncaught TypeError: Cannot read property '0' of undefined" is triggered when using toDataURL

Recently diving into the world of JavaScript and facing a perplexing error. I must be overlooking some fundamental concept... apologies in advance. Here is the issue at hand. In my HTML file, this snippet of code is present: <div> <script type= ...

Component not refreshing when state changes occur

I have a unique react application that resembles the one showcased in this codesandbox link https://codesandbox.io/s/eatery-v1691 By clicking on the Menu located at the bottom center of the page, it triggers the display of the MenuFilter component. The M ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Error: Unable to access the 'then' property of an undefined object when working with promises

I'm developing a website project that serves as a "Walmart" version of AirBnB. Here's the functionality of the button in question: When a user clicks on the "Make Reservation" button on a listing, they are prompted to select a start and end dat ...

Mapping the response from an http.get call to create a new typed object instance in Angular 2

Can anyone help me understand how to map the result from a service call to an object using http.get and Observables in Angular 2? Please check out this example In my getPersonWithGetProperty method, I am trying to return an Observable of type PersonWithG ...

utilizing the identical characteristics of the parent component

In order for the properties in InputGroup.js to be accessible as this.props in lower-level components like TextInput.js, Checkbox.js, I have created a simple component called InputComponent.js. In this component, I assign this.props to this.prpt so that it ...

Retrieve the document id along with the corresponding data from a collection

Retrieving data from the collection leads and displaying all documents in an HTML table. Upon clicking, I need to extract the document ID of the clicked item as it serves as the sole primary key. P.S I am able to obtain records of all documents in an arra ...

Activating JavaScript in the browser only when a button is manually clicked, not by default

As I work on my website, which is currently being constructed, I rely heavily on JavaScript. However, a concern of mine is the potential for failure if a user has JavaScript disabled on their client side system. I understand that it is not possible to pro ...

Using HTML and CSS to create interactive icons that change color when clicked, similar to how a link behaves

Have you ever wondered if there's a way to make an icon act like a link when clicked, just like regular text links turning purple? And not just the last one clicked, but every single icon that gets clicked. Trying to use the :visited pseudo was unsucc ...

Issue with Jquery similar to javascript createElement

I am attempting to replicate the code below using jQuery: var newElem = document.createElement("div"); newElem.innerHTML = "DynaColumn"; newElem.className = "ui-state-default ui-corner-all"; return newElem; This is the jQ ...

I am looking to extract solely the numerical values

Programming Tools ・ react ・ typescript ・ yarn I am trying to extract only numbers using the match method But I keep encountering an error Error Message: TypeError: Cannot read property 'match' of undefined const age="19 years ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

Concealing the Submit Button During Server Processing (Issues with Binding?)

My Angular 2 form is set up to send data to the server asynchronously. I want to provide users with visual feedback during the waiting period by changing the blue 'submit' button to a greyed-out 'Please wait...' button. To achieve this, ...

A guide on utilizing Java's Collections to organize a list filled with objects from a class

Struggling to figure out how to properly sort this list. When I attempt to use Collections.sort(mylist);, an error surfaces that is beyond my comprehension due to my beginner status in Java. Myclass x1 = new Myclass("8", "12"); Myclass x2 = new Myclass("6 ...

Bringing someone else's codebase up to date from version 49 to the latest version

After fixing the naming errors, I'm still encountering some issues. You can view the expected page layout here: Here is my current progress: There seems to be some glitched triangles when scrolling, and I believe splitting face4's into two fac ...

Is there a way to sort through an array based on a nested value?

Within an array of objects, I have a structure like this: "times": [{ "id" : "id", "name" : "place", "location" : "place", "hours" : [ {"day": " ...