Match and populate objects from the array with corresponding items

Currently, I have an array and object containing items, and my goal is to check each item in the array to see if its path matches any of the object names. If a match is found, I push it into that object's array.

While this part is working fine, I am struggling with what to do when no match is found. In such cases, I want to create a new item based on the name of the array item and push it inside the object.

All my attempts so far have resulted in duplicated values, and I believe I need a third object or array, but I can't seem to figure it out.

Let me provide a clearer explanation:

cList = {
  "rList": {
    "Significant": [
      {
        "Path": "Significant\\Significant Charts",
        "Name": "Charts"
      }
    ]
  },
};

and

SSList = {
  value: [
    {
      "Name": "Test long name",
      "Path": "/someFolder/Test long name",
    },
    {
      "Name": "Untitled",
      "Path": "/Significant/Untitled",
    }
  ]
};

Here is my current code snippet:

for (var cFolder in this.cList.rList) {
        this.SSList.forEach((ssFile)=> {
          if(ssFile.Path.indexOf(cFolder) >= 0){
            this.cList.rList[cFolder].push(ssFile);
          }
        });
      }

The first item in SSList will not be pushed since it doesn't match any existing objects. My intention is to create a new array and push it inside rList.

var folderName = ssFile.Path.split("/");
this.cList.rList[folderName[1]].push(ssFile);

Answer №1

To achieve this, consider swapping the positions of your inner and outer loops

let located = false;
this.SSList.value.forEach((ssFile) => {
    for (var cFolder in this.cList.rList) {
        if(ssFile.Path.indexOf(cFolder) >= 0){
            located = true;
            break;
        }
    }
    if (located) {
        this.cList.rList[cFolder].push(ssFile);
    } else {
        folderName = ssFile.Path.split("/");
        if (!(folderName[1] in this.cList.rList))
            this.cList.rList[folderName[1]] = [];
        this.cList.rList[folderName[1]].push(ssFile);
    }
    located = false;
});

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

Tips on customizing the appearance of the dropdown calendar for the ngx-daterangepicker-material package

Is there a way to customize the top, left, and width styling of the calendar? I'm struggling to find the right approach. I've been working with this date range picker. Despite trying to add classes and styles, I can't seem to update the app ...

How can I incorporate external libraries such as pdfmake into my Angular 8 application using a CDN?

I have successfully integrated the pdfmake library into my Angular 8 project for client-side PDF generation. However, I noticed that this third-party library is significantly increasing the build size of my Angular app. In order to reduce the build size, ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Unable to access the correct item from local storage while a user is authenticated

I am facing an issue with retrieving the userid from local storage when a user is authenticated or logged in. The user id is not being fetched immediately upon logging in, and even when navigating from one page to another, it remains unavailable until I re ...

Troubleshooting a Docker EPERM issue while attempting to compile an Angular application within a container

Our team is currently in the process of containerizing our existing stack using Docker and Docker Compose. This is a simplified version of our Docker Compose file with the relevant services: version: '3.8' services: #FO angularproject: c ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

Running a Vue.js 3 application with TypeScript and Vite using docker: A step-by-step guide

I am currently facing challenges dockerizing a Vue.js 3 application using Vite and TypeScript. Below is my Dockerfile: FROM node:18.12.1-alpine3.16 AS build-stage WORKDIR /app COPY package.json ./ RUN yarn install COPY . . RUN yarn build-only FROM ngin ...

Pause after the back button is activated

Upon pressing the back button on certain pages, there is a noticeable delay (approximately 1-5 seconds) before the NavigationStart event registers. I am utilizing the Angular RouterExtensions back() function for this action. Initially, I suspected that t ...

Can a custom CSS be linked directly to the angular-cli.json file?

I'm trying to incorporate custom CSS into my angular-cli.json file, but I haven't been able to find a successful method. I attempted to use the following code: "styles": [ "styles.css", "http://site.test/mycss.css" ], However, it does ...

Handling type errors with React Typescript MuiAccordion OnChange event handler

I'm a beginner in typescript and seeking advice on defining the type for an event handler. I have a component that utilizes material ui Accordion and triggers the handler from a container. Therefore, I need to specify the type of handleChange in my co ...

The process of setting up a dynamic cursor in ReactFlow with Liveblocks for precise zooming, panning, and compatibility with various screen resolutions

The challenge lies in accurately representing the live cursor's position on other users' screens, which is affected by differences in screen resolutions, zoom levels, and ReactFlow element positioning as a result of individual user interactions. ...

The text inside angular spans mysteriously vanishes

I have encountered an issue while working on my Angular Project. Previously, the <span> elements were displaying their contents without any problems. However, now I am facing an issue where the contents of <Span> elements are not visible. For ...

Deleting a file from the assets folder in Angular for good

I am attempting to permanently delete a JSON file from the assets folder using my component. Despite trying to use HttpClient, I encounter no errors but the file remains undeleted. constructor(http: HttpClient){} remove() { this.http.delete('assets ...

Steps for creating a TypeScript project for exporting purposes

Forgive me for my lack of experience in the js ecosystem. Transitioning from static languages to typescript has been a positive change, though I still find myself struggling to grasp the packaging/module system, especially when coupled with typescript defi ...

External node modules written in TypeScript can occasionally be transpiled into both `module.exports` and `

Currently, I am in the process of transforming my node application to utilize TypeScript external modules. While everything runs smoothly when executing the app, I encountered an issue with my mocha tests "exploding" after converting some of my .ts files d ...

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...

What is the process of creating a typeorm relationship between orders and products?

My Orders Entity file in TypeOrm looks like this: @Entity('orders') export class OrdersEntity { @PrimaryGeneratedColumn('uuid') id: string; @CreateDateColumn() created: Date; @UpdateDateColumn() updated: Date; @Column('t ...

Utilize useState and useEffect to efficiently sort through an item list based on its current state

I am currently working on an application where I have a list of items and I need to create a details page for each item when clicked. I am facing some challenges in implementing this functionality using useState, useEffect, and typescript. I have previousl ...

Displaying an array within an array using JSON syntax

Forgive me for asking, I'm still learning the ropes here. I need help displaying the add address (RED Circle). I can figure out how to display everything else except for this specific red circled part which seems like a separate array that I am not f ...