Combine two arrays and collapse one of the nested elements

I need help merging two arrays based on ID and flattening one of the objects. I haven't been able to find a solution for my specific case.

This is what I'm attempting and what I've managed to achieve so far:

const a = {
    someProperty: 'something',
    anotherProperty: 'somethingelse',
    listOfUsers: [
        { id: 100, a1: 'somea1', a2: 'somea2'},
        { id: 101, a1: 'somea1', a2: 'somea2'},
        { id: 102, a1: 'somea1', a2: 'somea2'},
        { id: 103, a1: 'somea1', a2: 'somea2'}
    ]

}
const b = [
    { id: 100, b1: { b2: 'someB2', b3: 'someB3'}},
    { id: 101, b1: { }},
    { id: 102, b1: { b2: undefined, b3: 'someB3'}}, 
    { id: 103, b1: { b2: 'someB2', b3: 'someB3'}}
]

const aAndB = a.listOfUsers.map(item => ({
    ...item,
    b_role: { ...b.find((itemInner) => itemInner.id === item.id) }
}));

The result I currently get is:

{
    id: 100, a1: 'somea1', a2: 'somea2',
    b_role: {b2: 'someB2', b3: 'someB3'}
}

{
    id: 100, a1: 'somea1', a2: 'somea2',
    b_role: {}
}

However, my desired output is:

{
    id: 100, a1: 'somea1', a2: 'somea2',
    b_role: 'someB2'
}

{
    id: 100, a1: 'somea1', a2: 'somea2',
    b_role: undefined
}

Is there a way to achieve this? I am open to using underscore if it can help.

Answer №1

Hello there, below is a functioning example:

const dataA = {
    someValue: 'something',
    anotherValue: 'somethingelse',
    userList: [
        { id: 100, b1: 'someb1', b2: 'someb2'},
        { id: 101, b1: 'someb1', b2: 'someb2'},
        { id: 102, b1: 'someb1', b2: 'someb2'},
        { id: 103, b1: 'someb1', b2: 'someb2'}
    ]
}
const dataB = [
    { id: 100, item1: { element2: 'someElement2', element3: 'someElement3'}},
    { id: 101, item1: {} }, //possible to be blank,
    { id: 102, item1: { element2: undefined, element3: 'someElement3'}}, //element2 can be undefined
    { id: 103, item1: { element2: 'someElement2', element3: 'someElement3'}}
]

let resultArray = [];
dataA.userList.map(aItem => {
   dataB.map(bItem => {
      if (bItem.id === aItem.id) {
         let output = {};
         output.id = aItem.id;
         output.b1 = aItem.b1;
         output.b2 = aItem.b2;
         output.role = bItem.item1.hasOwnProperty('element2') ? bItem.item1.element2 : undefined;
         resultArray.push(output);
      }
   })
})

console.log(resultArray)

Answer №2

Here is a code snippet for testing purposes with different values:

const x = {
  someProperty: 'something',
  anotherProperty: 'somethingelse',
  usersList: [
    { id: 100, x1: 'somex1', x2: 'somex2'},
    { id: 101, x1: 'somex1', x2: 'somex2'},
    { id: 102, x1: 'somex1', x2: 'somex2'},
    { id: 103, x1: 'somex1', x2: 'somex2'}
  ]
};

const y = [
  { id: 100, y1: { y2: 'someY2', y3: 'someY3'}},
  { id: 101, y1: { }}, //can be empty,
  { id: 102, y1: { y2: undefined, y3: 'someY3'}}, //y2 can be undefined
  { id: 103, y1: { y2: 'someY2', y3: 'someY3'}}
]

const xAndY = x.usersList.map(item => ({
  ...item,
  role_y: y.find((innerItem) => innerItem.id === item.id).y1.y2
}));

console.log(xAndY);

[
  { id: 100, x1: 'somex1', x2: 'somex2', role_y: 'someY2' },
  { id: 101, x1: 'somex1', x2: 'somex2', role_y: undefined },
  { id: 102, x1: 'somex1', x2: 'somex2', role_y: undefined },
  { id: 103, x1: 'somex1', x2: 'somex2', role_y: 'someY2' }
]

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

Laravel has not been properly initialized

Recently, I've been exploring Laravel 5.3 and vue.js and I'm trying to make a GET request to fetch some user data from my database. I'm utilizing components in this project. Here is a snippet from my app.js file: require('./bootstrap ...

Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls. Check out this directive: gameApp.directive('mapActivity', function() { return { restrict: 'A', link: function(scope, element, att ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Using AngularJS to Apply a Class with ng-repeat

Using ng-repeat in my markup, I am trying to add text to each li element and also include an additional class (besides the 'fa' class). This is what I have done so far: <ul class='social-icons' ng-repeat="social in myCtrl.socialArr" ...

Utilizing JavaScript/jQuery to activate a Bootstrap navbar post-page load

Having trouble triggering Bootstrap's navbar with plain JavaScript/jQuery while using Bootstrap 3.3.6 and jQuery 1.11.3. The data structure provided for my application cannot be modified in terms of adding classes or ids. <ul> <li ...

Struggling to generate a div using my JS/jQuery code

Currently working on a post-it web application to improve my skills in JavaScript and jQuery. I've encountered a few errors that have me stumped. Although I'm new to StackOverflow, I often use it as a helpful resource. You can find the code here ...

Loading V-Select with Data from JSON Using Vue.js

I tried to populate my v-select multiselect element using a JSON object, but unfortunately it did not work as expected. Here is the result I encountered: https://i.sstatic.net/kd1Gl.png <v-select v-model="serviceValues" :items="serviceO ...

Instructions for altering the hue of a canvas square when the cursor hovers over it

I want to implement a feature where the color of a tile changes when the user hovers their mouse over it, giving it a whitened effect. The tileset I am using consists of 32x32 tiles. Below are the scripts for reference. MAP.JS function Map(name) { ...

What is the best way to access the dimensions of a parent element in React with Hooks?

I am currently working on a new component and I am facing the challenge of obtaining the width and height of its parent <div>. Since all my components are functional ones using Hooks, the examples I found involving classes do not fit my case. Here i ...

Stop and start an Express.js server using the original port number

Currently, my Node.js application utilizes Express.js to handle incoming connections. The code snippet looks something like this: const express = require("express"); var server = express(); server.get("/test", (req, res) => testResponse(req, res)); ser ...

Using AJAX, FLASK, and JavaScript to send an existing array to an endpoint

Having trouble POSTing the array songFiles generated by the getTableData() function (inside an ajax request) to the /api/fileNames endpoint, and then handling it in the postFileNames() callback function. Any assistance or alternative approaches would be gr ...

Error: stripe.redirectToCheckout does not exist and cannot be executed

Can anyone help me with implementing Stripe checkout for a website? I've been struggling because the Stripe documentation is incomplete. Here's what I have so far: import React from 'react'; import { loadStripe } from '@stripe/stri ...

Vuejs allows objects to trigger the execution of methods through elements

My goal is to utilize a function in order to individually set the content of table cells. In this specific scenario, I aim to enclose the status with the <strong> - Tag (I refrain from modifying the template directly because it is stored within a com ...

Error: The property 'getClientRects' cannot be read because it is null

I'm brand new to learning about React and I've been attempting to incorporate the example found at: Unfortunately, I've hit a roadblock and can't seem to resolve this pesky error message: TypeError: Cannot read property 'getClient ...

Restrict dropping items in HTML5 by only allowing the drop if the target div is

I am working on developing a user-friendly visual interface for creating simple graphics. The interface includes 10 image icons and 5 boxes where users can place these icons. Users have the freedom to select which icon they want to display and arrange them ...

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

Flask does not provide a direct boolean value for checkboxes

After struggling for a week, I am still lost on where to make changes in my code. I need the checkbox to return a boolean value in my Flask application. Below are snippets of the relevant code: mycode.py import os, sqlite3 from flask import Flask, flash ...

npm Error: The installation script for [email protected] has encountered a failure

I encountered an error while attempting to execute "ionic start MyApp" in the Windows terminal. This is a new machine and I have already reinstalled nodejs and ionic, but the same error persists. Can someone lend a hand? npm WARN tar invalid entry & ...

The Vue.js application appears to be functioning properly with no error messages, however

Currently, I am in the process of learning Vue. Recently, I came across a helpful tutorial that I've been trying to implement using the standard vue-cli webpack template by splitting it into single file components. Despite not encountering any errors ...

Managing form submissions using Material UI and Next.js

Can someone provide insights on using Material UI with Next Js? I am experimenting with a Login template from Material UI, but I am facing an issue where query params are added to the URL upon Submit. For example: localhost:3000/auth/login changes to: ...