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 for combining multiple arrays into a single array

Looking for a way to read and organize employee details from a text file? I have created a subroutine that reads each line into a temporary array and now want to group every 5 lines/items into one array of type string. How can this be achieved? For exampl ...

Issue with bootstrap modal new line character not functioning properly

Is there a correct way to insert a new line for content in a modal? I have this simple string: 'Please check the Apple and/or \nOrange Folder checkbox to start program.' I placed the '\n' newline character before "Orange," e ...

What is the best way to convert a series of sentences into JSON format?

I'm struggling with breaking down sentences. Here is a sample of the data: Head to the dining room. Open the cabinet and grab the bottle of whisky. Move to the kitchen. Open the fridge to get some lemonade for Jason. I am looking to format the outc ...

Is it possible to attach "traits" to a current array of objects using TypeScript?

I have a variety of object types that I need to manipulate within an array consisting of those object types. type AB = { a:number, b:number} type CD = { c:number, d:string} type DE = { d:number, e:boolean} let state: AB[] = [] function onStateChange(newSt ...

Error message: Cordova not found - unable to use 'ionic native' 3 for CRUD operations with SQLite database

I am attempting to manage CRUD data with SQLite in Ionic 3, but unfortunately cordova is not functioning as expected. https://i.sstatic.net/5m411.png ...

The method of reading a unique array of objects for each radio button

Currently, I am facing an issue when trying to retrieve unique elements for each radio button from the database. The data structure and information obtained from the database are as follows: { FormularID: 182, CampaignID: 14, FormLabel: & ...

Execute .mts files using ts-node

Can ts-node be used to run .mts files? I attempted to do so, but encountered errors with imports (within the .mts file). Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. I am hesitant t ...

Utilize TypeScript to retrieve the enumeration values as a parameter through a method that employs a generic enum type

Is there a way to retrieve all values of an Enum (specified as a parameter or generic) and return them in a list? Additionally, if the user has a specific role, I only need to retrieve certain Enum values provided as a parameter. I had the idea of groupin ...

Utilizing electron and Systemjs to import node modules

Is it feasible for systemjs to utilize require("remote").require("nodemodule") when the module cannot be located in its registry? A similar mechanism seems to be functioning when utilizing electron with typescript and commonjs modules... Has anyone succe ...

Encountering a problem while trying to incorporate Mapbox GL JS into an Angular 8 web application

I'm currently working on incorporating mapbox into my simple web application, but I'm encountering difficulties when attempting to add it. At this point, I've already created a mapbox service and a map component. My approach involved using ...

Ensuring type safety in React using TypeScript

Within the code snippet below, I have specified that setLocale should be passed a value of type Locale through LocaleContextValue. However, why does the setLocale function not throw an error if no value is provided as a parameter? Even when I change it t ...

Ways to access attribute from a JSON object in PHP

The JSON data provided is a sample that includes various details such as name, date of birth, phone number, SSN, driver's license number, and address. [{"@attributes":{"id":"F11D-6T47"},"Name":{"FirstName":"Praveen", "MiddleName":{},"LastName":"Induk ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

What is the best way to choose a dropdown item at random from a list using Angular 5?

My current setup involves a list that looks like this... export const inventory= [ 'coffee' 'tea' 'wine' 'beer' 'sake' .... ]; Within the HTML, I am using a loop to create dropdown menus a set number of t ...

Adding values and using heapsort to organize them within an array-based heap

I've been working on creating a binary heap using arrays. I have successfully implemented the heap with the buildHeap and heapify functions. However, I've encountered issues when trying to insert a new element into the array using the insert func ...

Setting up admin credentials with TypeScript in Firebase cloud functions

While working with Firebase cloud functions in JavaScript, I utilized the following code snippet to initialize admin: admin.initializeApp({ credential: admin.credential.cert(require('./key/firebase-adminsdk.json')), databaseURL: "https://app ...

Add photos to a Google Cloud bucket through an Angular 7 application

Can anyone help me figure out how to upload an image to a Google Cloud bucket within an Angular 7 app that doesn't utilize Node.js as the backend, but instead uses Firebase as a backend service? I've searched for guides and documentation but have ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

transferring scoped model information to the controller

When using AngularJS, my view is structured like this: <div class="sli1" ng-init="values=[10,20,30,40,50]" <div class="sli2" ng-init="values2=[10,20,30,40,50]" I am attempting to send the initial data models back to the controller for retrieva ...

Adding a value to an array in TypeScript

When trying to add values to an array in my code, I encountered an error stating that "number" is not a valid type for the array. someArray: Array <{ m: number, d: Date}> = []; this.someArray.push(500,new Date(2020,1,15)); ...