A guide to checking an array of objects by their ID and assigning a new property using JavaScript

I am working with two arrays of objects called arr1 and arr2

If the ID in both arr1 and arr2 matches, I want to add the property names from arr1 to arr2 using JavaScript

var arr1 = [
  {id: 1, name : "Helena"},
  {id: 2, name : "John"}
]

var arr2 = [{ 
  country: "MY", 
  details: [{
    mode: "parttime",
    members:[{id:1}, {id: 2}]
  }]
}]

The expected output should look like this:

[{ 
  country: "MY", 
  details:[{
    mode: "parttime",
    members: [
      {id:1, name: "Helena"},
      {id: 2, name: "john"}
    ]
  }]
}]

Answer №1

Take a look at this:

var arr1 = [
  {
    id: 1,
    name: "Sarah",
  },
  {
    id: 2,
    name: "Michael",
  },
];

var arr2 = [
  {
    country: "US",
    details: [
      {
        mode: "full-time",
        members: [
          {
            id: 1,
          },
          {
            id: 2,
          },
        ],
      },
    ],
  },
];

function getPeopleByCountry(teamArr, countriesArr) {
  // map each country object in the array to a new country
  return countriesArr.map((country) => {
    return {
      ...country, 
      // modify country.details by mapping it to a new object
      details: country.details.map((detail) => {
        return {
          ...detail, 
          // modifying members
          members: detail.members.map((member) => {
            const memberObj = { ...member };
            // check if name exists for this member
            const name = teamArr.find((i) => i.id === member.id).name;
            if (name) {
              memberObj.name = name;
            }
            return memberObj;
          }),
        };
      }),
    };
  });
}

console.log(getPeopleByCountry(arr1, arr2));

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

Implementing form validations using JavaScript for a form that is created dynamically

I have dynamically created a form using javascript and now I need to add mandatory validations on the form. The validations should trigger when the dynamically created button is clicked. However, I am facing an issue where I receive an error whenever I t ...

What is causing the duplication of leaves when using this DFS implementation?

I created an algorithm to compare if two trees have the same leaves. https://i.sstatic.net/lpO2C.png Both trees display matching leaf numbers in the exact order, resulting in a true outcome. Below is the code that I formulated: function leafSimilar(root ...

ApolloError: Undefined fragment detected and unable to be used

Within the complex structure of my application, I encounter the following: import { gql } from '@apollo/client'; gql` fragment StuffTable on Stuff { id status } `; export const GetStuffDocument = gql` query GetStuff($id: ID!) { ...

Organizing a collection of string dictionaries in Swift

I have an array of dictionaries in Swift that I need to sort based on the value of the "Timestamp" key in each dictionary. Here is the structure of my data: [ [ "DateTime": "8/16/16, 4:00 PM", "Owner": "Teacher1", "Subject": "A ...

express/node: You are unable to define headers once they have already been sent to the client

I seem to be running into a problem with my expressJS application. Every time I try to post to a specific route, I keep getting the error message Cannot set headers after they are sent to the client. I've been troubleshooting this issue but can't ...

Update search results when performing a new search on a web application (without using jQuery)

My simple web app interacts with an API to retrieve search results from a database and utilizes ajax to insert them into an empty ul element on the page (employing JSONP for cross-domain requests). I am struggling to achieve this functionality using plain ...

What could be causing my YAML value to be undefined when I try to read it in JavaScript, despite it being defined in every other

I have been attempting to access a YAML file from my local directory. While I am able to read the file, the data within it appears to be undefined. The error message that I am encountering is as follows: https://i.sstatic.net/yXC0H.png Here is an exampl ...

What is the best method for removing table rows with a specific class?

I have an html table with several rows, and for some of these rows the class someClass is applied. My question is: How can I delete the rows that have a specific class? <table> <tr class="someClass"> ...</tr> <tr class="someClass"> ...

The functionality of the AngularJS nested router is not functioning properly

I am encountering some challenges with Angular routing, specifically when using nested routes: The current 'abc' state works flawlessly for the route /admin/team/:teamId .state('admin', { url: '/admin', controller: & ...

Is it possible to declare an array with a non-constant length?

I'm a bit confused about how to declare arrays in C. I understand that you can declare arrays like this: int a[20]; // Allocates space for an array of 20 integers int b[] = {32, 431, 10, 42}; // Length is automatically calculated based on the number ...

What could be the reason for the lack of rendering in this imported React component using System.import?

I've been experimenting with dynamic code splitting using webpack 2 and react. As part of my testing, I decided to create a component that fetches code asynchronously: import React, { Component } from 'react' export class Async extends Com ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

Error encountered due to an unset offset on an array that was previously displayed?

I am encountering an issue with the behavior of my code. Within a loop, I am checking if the array contains an 'data' index. If it does not exist, I attempt to identify the previous, next, and current values in the array. What is confusing me is ...

Performing addition and subtraction calculations with HTML and Javascript

I need help creating a simple HTML table for adding and subtracting values, with a limit of 10 and a minimum of 0. I have two functions set up, additionalAdd and additionalSub, triggered by the onclick event, but I keep getting an error saying that totalAd ...

A different approach to splitting strings

After receiving a GET request, I am presented with a string that has the following format: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://myUrl.com">you said:This is a test --&gt;SHA1:7d9d2886509cfd1dfd3c693fff43b82561ec00a18 ...

Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be. Here i ...

React's setState method may not trigger a re-render

I am currently working on a personal project using React for the front-end and Node for the back-end. One part of the application involves counting the entries when a user submits an image URL, updating it on the server, and then re-rendering it on the fro ...

Vue Router generates a URL containing %2F when dealing with slug routes

I am facing an issue in my Vue 3 application where I need to create a route for dynamic slugs. Currently, when using RouterLink, the generated URL contains %2F instead of actual slashes which is not the desired result. For example, the current URL looks l ...

You cannot reassign NodeJS global variables

Currently, I am in the process of writing unit tests for code that utilizes a JavaScript library. This particular library sets a global variable if it does not already exist using the following pattern: var GLOBAL_VAR = GLOBAL_VAR || {} While this method ...

Implementing a post request triggered by a button click in Node.js with Express

How can I invoke a controller from a button click event? I tested it in Postman and it works fine, but I'm having trouble calling it from a button on my front-end. I am using Nodemailer and Node Express to send emails. Here is my code. Can someone p ...