Combining two arrays based on a common id

Here are two arrays:

var members = [{docId: "1234", userId: 222}, {docId: "1235", userId: 333}];
var memberInfo = [{id: 222, name: "test1"}, {id: 333, name: "test2"}];

I want to merge them into a single array by matching user ids programmatically.

The combined array should look like this:

var finalArray = [{docId: "1234", userId: 222, name: "test1"}, {docId: "1235", userId: 333, name: "test2"}]

I am looking for a more efficient way to do this. I have the underscore library in my application but couldn't find a clean method to achieve this.

Answer №1

A method utilizing underscore:

var updatedArray = _.map(members, function(person){
    return _.extend(person, _.omit(_.findWhere(personalInfo, {id: person.userId}), 'id'));
});
  1. _.map iterating over the members
  2. locating the corresponding personal information using _.findWhere
  3. _.omit removing the id key from the found personal info
  4. _.extend merging the member with their personal info

Answer №2

To accomplish this task, you can utilize the foreach function along with creating a third array to display the desired information.

$scope.members = [{docId: "1234", userId: 222}, {docId: "1235", userId: 333}];
$scope.memberInfo = [{id: 222, name: "test1"}, {id: 333, name: "test2"}];
$scope.finalArray = [];

angular.forEach($scope.members, function(member) {
    angular.forEach($scope.memberInfo, function(memberInfo) {
      if(member.userId ==memberInfo.id) {
          var test = {
            docId : member.docId,
            userId: member.userId,
            name: memberInfo.name
          }
          $scope.finalArray.push(test);
      }
  });
});

For a live example, check out this plunker:

http://embed.plnkr.co/QRB5v2cI6SZOdZgdqDVR/preview

I hope this solution is helpful!

Answer №3

function updateMemberNames(members, memberInfo) {
  return members.map(function(member) {
    member.name = memberInfo[findMemberById(member.id, memberInfo)].name
    return member
  })

  function findMemberById(id, elements) {
    var index = elements.filter(function(element) {
      return element.id === id
    })[0]
    return elements.indexOf(index)
  }
}

console.log(updateMemberNames(members, memberInfo))

Answer №4

const teamMembers = [{
    docId: "1234",
    userId: 222
}, {
    docId: "1235",
    userId: 333
}];
const memberInfoDetail = [{
    id: 222,
    name: "John Doe"
}, {
    id: 333,
    name: "Jane Smith"
}];
const finalMemberArray = [];

_.each(memberInfoDetail, function (person) {
    finalMemberArray.push(_.each(_.where(teamMembers, {
        userId: person.id
    }),

    function (member) {
        member.name = person.name
    }));
});

console.log(finalMemberArray);

Check out the Fiddle example here

Answer №5

With ES6, you can utilize the .find method along with Object.assign() within vanilla JavaScript without relying on any additional libraries.

let updatedArray = [];
memberInfo.forEach(member => {
updatedArray.push( Object.assign( {}, member, 
         { docId: members.find(m => m.userId === member.id).docId } 
    ))
});

Answer №6

Perform a nested mapping operation and add a new field called date to the main element when matching fields are found in the arrays.

member.map(mem => {
    return memberInfo.map(info => {
        if (info.id === mem.userId) {
            mem.date = info.date;
            return mem;
        }
    }
}

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

Creating a Search Functionality within a Tab Component in Ionic

I'm currently facing an issue with adding a search bar under the "Search" tab in my project. I've tried implementing similar logic to what's shown here, but it doesn't seem to function properly when using the ionic serve --lab live in-b ...

Exploring paths deep within by employing wildcards as a query

I have data structured according to Firebase's flat structure advice, storing quotes in nodes like this: quotes -> clientName -> quoteObject Each 'quoteObject' includes a 'dateCreated' value that I aim to retrieve as follow ...

Guide on submitting a form via Ajax on a mobile app

Looking for a way to submit the form located in components/com_users/views/login/tmpl/default_login.php using Ajax. <form action="<?php echo JRoute::_('index.php?option=com_users&task=user.login'); ?>" method="post"> <fie ...

What is causing the issue with useForm not being identified as a function?

error image Why is this error occurring when attempting to use useForm: ⨯ src\app\journal\page.tsx (18:53) @ useForm ⨯ TypeError: (0 , react_hook_form__WEBPACK_IMPORTED_MODULE_5__.useForm) is not a function at Page (./src/app/journal/pa ...

HTML login form featuring a transparent design with a username textfield already populated with a cookie

Hey there! I'm in the process of creating a simple website for my university. I need to include a login form where users can enter their username and password. If the credentials are correct, a cookie is set with the username value. This way, when the ...

Strategies for resolving type issues in NextJs with Typescript

In my project using Next.js with TypeScript, I encountered an issue while trying to utilize the skipLibCheck = false property for enhanced checking. This additional check caused the build process to break, resulting in the following error: Error info - U ...

Import Socket.io into your Node.js application using the import statement

Can't seem to figure out why I keep encountering this error. Everything works perfectly when I use the request method instead. import express from 'express'; import { createServer } from 'http'; import * as io from 'socket.io& ...

The functionality of "Body Onload" for sending "ScrollHeight" is malfunctioning in Chrome and Safari

I came across an issue where the iframe_resize function in my code was not working as expected. After investigating further, I realized that the problem did not lie with the function itself. So, I decided to post a new question. Within my index.html file ...

Can you effectively link together AngularJS promises originating from various controllers or locations?

Attempting to explain in as much detail as possible, the configuration file config.js contains the following code snippet: .run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $loca ...

Unlimited Angular Digest Loop Caused by promise.then()

The issue: The usage of this.promise.then(function(){}) function within a controller method appears to lead to an infinite digest loop on $rootScope, even though the returned value remains constant. It should be noted that removing the .then() line elimina ...

I am interested in retrieving all users along with the places they have created using virtual population

const fetchAllUsers = async (request, response) => { try { await User.find({}).populate('place').exec(function(err, data) { console.log(data.places) console.log(data) res.json(&quo ...

Transforming a callback function into a Promise: A step-by-step guide

I'm currently utilizing Bluebird promises and attempting to make the following function work with Promisify: var jwt = require('jsonwebtoken'); function _test_encode() { var cert = fs.readFileSync('public.pub'); return j ...

Express.js post request not functioning properly

I am currently in the process of developing a discussion-based Node.js/Express app and I am focusing on creating a discussion page. I have been attempting to test if my discussion controller file is properly linked, but for some reason every time I click t ...

Unable to find the element using the text "selenium webdriver"

Currently, I am working with Selenium WebDriver using Java. Log.info("Clicking on To weekrange dropdown"); JavascriptExecutor executor25 = (JavascriptExecutor)driver; executor25.executeScript("document.getElementById('toWeekYear).style.display=' ...

perform the directive function following the ng-cloak execution

I am having an issue with my content using the ng-cloak directive, as I would like to retrieve the height of an element using innerHeight() within a directive. However, when I use innerHeight(), the element is hidden by ng-cloak so the result is always 0. ...

Is the JavaScript file not being stored in the cache?

As I work on optimizing my web application, I am facing a challenge with a javascript file size of approximately 450K even after compressing it. While I intend to redo the javascripting in due time, for now, I need to go live with what I have. Initially, I ...

Conceal the Initial Data Point in a Series on HighCharts

Is there a way to toggle the visibility of specific year columns in a chart using checkboxes? I've tried using the .hide() method but it doesn't seem to work for individual data points within the series. For example, I want to hide the 2018 colum ...

Navigating through Angular JS validation procedures step by step

I have a wizard in angular js consisting of multiple steps: <wizard on-before-step-change="log(event)" on-step-changing="log(event)" on-after-step-change="log(event)" user="user"> <step title="step 1"> </step> <step title="step 2"& ...

Navigating a table while keeping headers in place at the top

Trying to construct a table where the thead remains fixed while the tbody scrolls. Utilizing percentages and fixed width for cell size determination, aiming for uniformity and alignment between percentage td's and thead headers. Referenced JSFiddle d ...

Turn off the scrolling bars and only allow scrolling using the mouse wheel or touch scrolling

Is there a way to only enable scrolling through a webpage using the mouse wheel or touch scrolling on mobile devices, while disabling browser scroll bars? This would allow users to navigate up and down through div elements. Here is the concept: HTML: &l ...