Combining the results of JavaScript comparisons into a unified object array and adding a new value if it matches an existing value within the same

I am interested in consolidating the array to represent the base folder hierarchy.

In the array provided, "Level 1" is the lowest level with no children folders. The "other level" contains various folders all under the "Top Level."

The array structure is as follows:

[{ id: "Top Level", outerpath: "test plan", innerpath: "Regression" },
 { id: "other level", outerpath: "Regression", innerpath: "area 1" },
 { id: "Level 1", outerpath: "area 1", innerpath: "Subarea 1" },
 { id: "Level 1", outerpath: "area 1", innerpath: "Subarea 2" },
 { id: "Level 1", outerpath: "Regression", innerpath: "area 2" }]

I wish for the concatenated data within the object array to appear as follows:

test plan/Regression/area 1/Subarea 1
test plan/Regression/area 1/Subarea 2
test plan/Regression/area 2

I am unsure of how to begin this process. Could it involve looping through the array, matching "innerpath" and "outpath" values, then adding the completed data to another array?

Any insights or suggestions would be greatly appreciated.

UPDATE:

To elaborate on my query, the array is dynamic based on API results and may look like the following:

[{ id: "Top Level", outerpath: "test plan", innerpath: "Regression" }
{ id: "other level", outerpath: "Regression", innerpath: "area 1" }
{ id: "Level 1", outerpath: "area 1", innerpath: "Subarea 1" }
{ id: "other level", outerpath: "area 1", innerpath: "Subarea 2" }
{ id: "Level 1", outerpath: "Regression", innerpath: "area 2" }
{ id: "Top Level", outerpath: "test plan", innerpath: "other testing" }
{ id: "Level 1", outerpath: "other testing", innerpath: "other testing area 1" }
{ id: "other level", outerpath: "other testing", innerpath: "other testing area 2" }
{ id: "Level 1", outerpath: "other testing area 2", innerpath: "other testing subarea 1" }
{ id: "Level 1", outerpath: "Subarea 2", innerpath: "SubSubArea 1" }]

There could be multiple top levels, as the folder "test plan" will have several folders, some with their own subfolders.

https://i.sstatic.net/gqmCo.png

Here is the code that organizes the data retrieved from the API callback:

let testSuiteData = res;
           testSuiteData.value.forEach(async testSuiteItem => {
                  console.log(testSuiteItem);
    
                  if(!testSuiteItem.hasChildren === true) // Level 1
                  {
                      console.log(testSuiteItem.parentSuite.name + '/' + testSuiteItem.name)
                      folderHierarchy.path.push({
                          id: 'Level 1',
                          outerpath: testSuiteItem.parentSuite.name,
                          innerpath: testSuiteItem.name
                      })
                            
                  }
                  else if(testSuiteItem.hasChildren === true ) // other levels
                  {
                      if(testSuiteItem.parentSuite.name === testSuiteItem.plan.name) // Top Level
                      {
                          console.log(testSuiteItem.parentSuite.name + '/' + testSuiteItem.name)
                          folderHierarchy.path.push({
                              id: 'Top Level',
                              outerpath: testSuiteItem.parentSuite.name,
                              innerpath: testSuiteItem.name
                          })
                      }
                      else{ // Other Levels
                          console.log(testSuiteItem.parentSuite.name + '/' + testSuiteItem.name)
                          folderHierarchy.path.push({
                              id: 'other level',
                              outerpath: testSuiteItem.parentSuite.name,
                              innerpath: testSuiteItem.name
                          })
                      }
                  }
    
                        
                  console.log(folderHierarchy.path);

Answer №1

To streamline this process, we can first compile a list of unique innerpath values that do not overlap with any outerpath values and then trace back from each one.

Here's an example using your most recent dynamic array of objects:

I opted to omit the id property values from your original data for simplicity in this instance, but feel free to reintegrate them in your final iteration if necessary.

const data = [
  { outerpath: "test plan", innerpath: "Regression" },
  { outerpath: "Regression", innerpath: "area 1" },
  { outerpath: "area 1", innerpath: "Subarea 1" },
  { outerpath: "area 1", innerpath: "Subarea 2" },
  { outerpath: "Regression", innerpath: "area 2" },
  { outerpath: "test plan", innerpath: "other testing" },
  { outerpath: "other testing", innerpath: "other testing area 1" },
  { outerpath: "other testing", innerpath: "other testing area 2" },
  { outerpath: "other testing area 2", innerpath: "other testing subarea 1" },
  { outerpath: "Subarea 2", innerpath: "SubSubArea 1" }
];

const outerpaths = data.map(({ outerpath }) => outerpath),
      innerpaths = data.map(({ innerpath }) => innerpath).filter(innerpath => !outerpaths.includes(innerpath));

const concatenated = innerpaths.map(innerpath => {
  let obj = data.find(obj => obj.innerpath === innerpath),
      str = obj.outerpath + '/' + innerpath;
  if (obj) do {
    obj = data.find(({ innerpath }) => obj.outerpath === innerpath);
    if (obj) str = obj.outerpath + '/' + str;
  } while (obj)
  return str;
});

console.log(concatenated.join('\n'));

The resulting output is as follows:

test plan/Regression/area 1/Subarea 1
test plan/Regression/area 2
test plan/other testing/other testing area 1
test plan/other testing/other testing area 2/other testing subarea 1
test plan/Regression/area 1/Subarea 2/SubSubArea 1

Answer №2

One possible solution is outlined below:

const data = [{ category: "Top Level", parentCategory: "test plan", childCategory: "Regression" },
{ category: "other level", parentCategory: "Regression", childCategory: "area 1" },
{ category: "Level 1", parentCategory: "area 1", childCategory: "Subarea 1" },
{ category: "Level 1", parentCategory: "area 1", childCategory: "Subarea 2" },
{ category: "Level 1", parentCategory: "Regression", childCategory: "area 2" }];

const categoryMap = {};
const topLevelData = data.splice(0, 1)[0];
const baseCategory = `${topLevelData.parentCategory}/${topLevelData.childCategory}`;

for (let i = 0; i < data.length; i++) {
    const splitCategories = data[i].parentCategory.split(' ');
    const key = splitCategories[1] ? splitCategories[1] : splitCategories[0];

    if (!categoryMap[key]) categoryMap[key] = [];

    if (splitCategories[0] == 'area')
        categoryMap[key].push(`${baseCategory}/${data[i].parentCategory}/${data[i].childCategory}`);
    else if (splitCategories[0] == 'Regression')
        categoryMap[key].push(`${baseCategory}/${data[i].childCategory}`)
}

console.log(categoryMap);

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

Ways to maximize the amount of content contained within a box

My current struggle involves meeting the requirements of my customers. I have a small box (230px x 200px) with an image that will display a list on hover. However, the customer now wants more items in the list than can fit in the box. Scrolling within the ...

What is the best way to position two elements floated to the right in separate rows within a single row?

Having trouble with a web design issue. I am currently working on a website and trying to format an input field with a label so that the label sits on top of the input while floating to the right. However, I'm encountering difficulties as the elements ...

Leveraging Next.js to efficiently handle multiple asynchronous requests with NextResponse

I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 4 ...

Listcell XUL with button options

How can I make buttons inside a listcell function in XUL? I am having trouble getting it to work. Here is the XUL code: <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label ...

Navigating sub-domains swiftly

Having trouble setting up sub-domains and routing in Express Node. I need to direct users based on their device and browser type. If the user is on a desktop, they should be routed to web.. If they are on a mobile device, it should be mobile.. And if the ...

Achieving success with the "silent-scroll" technique

I've been struggling to implement the 'scroll-sneak' JavaScript code for quite some time now. This code is designed to prevent the page from jumping to the top when an anchor link is clicked, while still allowing the link to function as inte ...

Using Three.js to import and cast rays on a .obj model created in Blender

I have successfully imported a 3D terrain using Blender and the OBJLoader in Three.js. In addition, I have created a mesh (highlighted in yellow in the image below) that I want to follow the mouse cursor while it hovers over the terrain. I have attempted t ...

Expanding the number of buttons for <ul> in creating a responsive navigation system using Angular

My navigation consists of 8 items (li), and as the resolution shrinks, the items are pushed onto a new line. I am looking to implement a feature where if an item doesn't fit in the navigation anymore, a "MORE" dropdown button appears on the right side ...

Add numerical identifiers to numerous camera entities

I am working on a three js scene that includes a 3D model, and I would like to incorporate multiple cameras into the model. In order to distinguish between each of the cameras in the scene, I am looking for a way to label them with numbers, possibly near ...

``In JavaScript, the ternary conditional operator is a useful

I am looking to implement the following logic using a JavaScript ternary operation. Do you think it's feasible? condition1 ? console.log("condition1 pass") : condition2 ? console.log("condition2 pass") : console.log("It is different"); ...

Encountered an error in Discord.js: Undefined properties unable to be read (execute)

Here is the code snippet from my main file: const { Client, IntentsBitField, Collection, intents, SlashCommandBuilder } = require('discord.js') const { TOKEN, PREFIX } = require('./config.json') const fs = require('fs'); const ...

Heroku experiencing instability with Javascript/MySQL project during requests

Currently facing a problem with my Heroku API developed in JavaScript that interacts with a MySQL database. Previously operational, now encountering an error on each API request: 2020-06-17T18:37:13.493711+00:00 app[web.1]: > <a href="/cdn-cgi/l/ema ...

The initiation of jQuery animation through user interaction hinges on the completion of the preceding animation

In my project, I've designed a timeline that offers users the ability to zoom in and out by simply clicking on corresponding buttons. Since the timeline is too large to fit entirely on the screen, it is contained within a scrollable div. To ensure tha ...

While attempting to use JavaScript and AJAX to read a JSON object, I encountered an issue caused by the CORS

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Docu ...

`How can I extract information from the internet?`

I am attempting to retrieve data from the following URL: . My focus is on obtaining the raw data series rather than the data presented in tables and charts. Although the website provides a button for downloading a .csv file, I am unsure of how to automat ...

Unexpected behavior in Next.js when using Auth0: pageProps are empty when wrapped with withPageAuthRequired HOC

Explaining the Issue The problem arises when using withPageAuthRequired with getServerSideProps, as the pageProps object is empty. Despite following common practices, the pageProps parameter remains undefined. Expected Outcome Upon calling getServerSideP ...

The addClass and removeClass functions seem to be malfunctioning

Hey everyone, this is my first time reaching out for help here. I looked through previous questions but couldn't find anything similar to my issue. I'm currently working on a corporate website using bootstrap3 in Brackets. I've been testing ...

Angular Code Splitting with Webpack

My current project setup is causing some loading issues due to the large download size of Angular Material. As a result, a white screen remains loading for around 45 seconds. I have attempted to implement code splitting to enhance the loading speed of my a ...

Ways to retrieve the year and month from a given date

https://i.sstatic.net/EZy4e.pngI'm working with two forms. Form1 has an input field for a date and a button to validate the input. When the user clicks on the validate button, I want the year of the date to appear in the "Year" cells and the month to ...

In Vue Js, the function createUserWithEmailAndPassword does not exist within _firebase_config__WEBPACK_IMPORTED_MODULE_3__.default

My createUserWithEmailAndPassword function seems to be malfunctioning. Here is the code snippet I am using - config.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseCon ...