Guide to organizing elements in an array within a separate array

Our array consists of various items:

const array = [object1, object2, ...]

The structure of each item is defined as follows:

type Item = {
  id: number;
  title: string
  contact: {
    id: number;
    name: string;
  };
  project: {
    id: number;
    name: string;
  } | null;
};

Our goal is to organize the data into an array with the following structure:

type Contact = {
  id: number;
  name: number;
  project: Array<{
    id: number;
    name: number;
    items: Array<{
      id: number;
      title: number;
    }>;
  }>;
};

const array2 = [contact1, contact2, ...]

In each Item, if a project exists, it is associated with the contact of that specific item.

How can we efficiently map this data?

Answer №1

Ready for your orders!

function extractIdName(obj){
    return {id:obj.id,name:obj.name}
}

function restructure(arr){
    let o={}
    arr.forEach(e=>{
        console.log(e);
        if(!o[e.contact.id]) {
            o[e.contact.id] = extractIdName(e.contact);
            o[e.contact.id].project=[];
        }
        console.log(o[e.contact.id]);
        let ps=o[e.contact.id].project;
        let p = ps.find(project=>{
            return project.id==e.project.id;
        })
        if(!p) {
            p=extractIdName(e.project);
            p.items=[];
            ps.push(p);
        };
        console.log(p);
        p.items.push({id:e.id,title:e.title})
    })
    return Object.values(o);
}
console.log(restructure(array));

It would be more beneficial to incorporate an ordered map to confirm the existence of projects and contacts, though the current method is acceptable as long as each contact does not have a majority of the projects.

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

Adjusting the filter location in React-admin

This is the common method of implementing filters in react-admin https://i.stack.imgur.com/M8yq7.png However, in my particular scenario, I require the filters to be inside each column heading. For example: https://i.stack.imgur.com/GU2Pz.png The filter ...

Steps for accessing the "this" keyword within the parent function

Struggling with referencing `this` within a parent function while building a basic tab system using AngularJS. It seems like I may not have a solid grasp on the fundamentals, so any guidance would be appreciated: JavaScript: $scope.tabs = { _this: th ...

JavaScript Code for Executing Function on Checkbox Checked/Unchecked

My goal is to display an image when the checkbox is checked and show text when it is unchecked. However, I am facing an issue where the text does not appear when I uncheck the checkbox. <input type="checkbox" id="checkword" onchang ...

What is the process to activate strict mode for my entire package without applying it to dependencies?

Previously, I would always start my JavaScript files with "use strict"; to enable the strict mode. However, I am now faced with the task of applying this change to over 200 files in my NodeJS package, which seems like a daunting process. Is there a way to ...

Unable to establish breakpoints in TypeScript within VS Code

I seem to be facing an issue while trying to set breakpoints in my TypeScript nodejs app using Visual Studio Code. Despite following the guidelines provided on the Visual Studio Code website, I have not been able to achieve success. Below is the content o ...

Using JSON.parse in Node.js to manipulate arrays with Javascript

While taking an online course, I came across a confusing code snippet: notes = JSON.parse(notesString). The confusion arises from the fact that this code is supposed to result in an object, but it's being treated as an array. Isn't JSON.parse sup ...

In a JavaScript project, encountering an error when using FB.logout that states "The expression is undefined and not a function."

Seeking to integrate Login with FB into my react website. FB.init({ appId : app_id, cookie : true, xfbml : true, version : 'v5.0' }); Followed by FB.getLoginStatus(({status}) => { if (status === 'conn ...

Tips for Showing Websocket Response On Web Browser Using Node.js

Just starting out with NodeJS and here's my code snippet: const webSocket= require('ws'); const express = require('express'); const app=express(); Var url = "wss://stream.binance.com:9443/BTCUSDT@trade`" const ws = new webS ...

Discovering package utilities with npm commands

When integrating a package into my code, such as: import { Text, View, StyleSheet } from "react-native"; How can I discover the full range of utility functions like Text, View, etc. that are available in the react-native package? Is there an n ...

Is it possible to combine various SVG icons into a single component?

I am currently able to code SVGs in React-Native using typescript. This allows me to call them as individual react native components. Below is an example of my current capability: <View> <BackArrow color ="red" wid ...

Guide on saving a Facebook image to a web server directory with Node.js and Express

Looking for some help here - I'm trying to download and save images from a user's Facebook album onto my server folder. My server is running on node.js and express, but when I tried using http.get it didn't work. Any advice or solutions wou ...

In HTML5, a full-width video exceeds the size of the screen

When I have a video set to full width in a header with the width at 100%, the issue arises with the height. The video is too large, causing the controls to be out of view unless I scroll. Is there a solution to remedy this problem? <video width="100%" ...

Ensure that the value is updated upon clicking on the radio buttons and store the value in a session variable for

I'm working on a feature that involves two radio buttons: one for shipped and the other for not shipped. The requirement is that when the first radio button is clicked, an amount of 100 should be added to the total price. If the second radio button is ...

Seeking guidance for the Angular Alert Service

I'm relatively new to using Angular and I'm struggling to determine the correct placement for my AlertService and module imports. Currently, I have it imported in my core module, which is then imported in my app module. The AlertService functions ...

I have an empty array that needs to be filled with numbers

Currently, I am facing a challenge where I have an empty array and need to insert numbers from 1 to 20 into it. Once that is complete, the next step is to calculate the total sum of all these numbers. The stumbling block I am encountering lies in this sect ...

What is the best way to focus on a particular version of TypeScript?

After upgrading my Angular 2 project to RC1 and the router to v3 alpha3, I encountered the following errors: node_modules/@angular/router/directives/router_outlet.d.ts(10,14): error TS1005: '=' expected. It appears to be a TypeScript version is ...

Take away the dropdown selection once the form has been submitted

Every day, a user fills out a form ten times. They choose an option from the dropdown menu, fill out the form, and submit it. I am looking for a solution to either remove the selected option once it's been submitted or mark it as complete by highlight ...

Seasonal selection tool

I need a quarterly date picker feature, ideally using Angular. I am interested in something similar to the example shown below: https://i.stack.imgur.com/9i0Cl.png It appears that neither Bootstrap nor (Angular) Material have this capability. Are there a ...

The proper order for logging in is to first validate the login credentials before attempting

I created a custom validation class to verify if a user is logged in before allowing them access to a specific page. However, after implementing this validation, my program no longer routes me to the intended component. Validation.ts export class UserVal ...

Performing a `contains` operation with JQuery on this variable or object

Help! I'm completely confused about this problem. First, I am trying to use jQuery to select an li object and then check if a certain text exists within it using the "contains" function. However, for some reason, the line with the "contains" function ...