Traversing a deeply nested array of objects, comparing it with a separate array of objects

I am currently learning Javascript and facing a challenge involving looping through nested arrays of objects and filtering another array based on specific properties.

Let's take a look at the structure of both arrays:

const displayArr = {
   sections: {
      section_1: [
        {
          style: "single_select_cmp",
          definition: {
            table_name: "table_1",
            field_name: "organization",
          }
        },
      ],
      section_2: [
        {
          style: "single_select_cmp",
          definition: {
            table_name: "table_1",
            field_name: "title",
          }
        },
      ]
   }
};

const schemaArr = [
  {
    table_1: {
      columns: [
        {
          description: "Tracking Number Desc",
          display_name: "Tracking Number",
          display_type: "number",
          field: "tracking_number",
          type: "int"
        },
        {
          description: "Title Desc",
          display_name: "Title",
          display_type: "multiple lines of text",
          field: "title",
          type: "text"
        },
        {
          description: "Description Desc",
          display_name: "Description",
          display_type: "multiple lines of text",
          field: "description",
          type: "text"
        },
        {
          description: "Organization Desc",
          display_name: "Organization",
          display_type: "single line of text",
          field: "organization",
          type: "text"
        }
     ]
   }
 },
 {
  table_2: { columns: [ {...}, {...} ] }
 },
 {
  table_3: { columns: [ {...}, {...} ] }
 }
 ...
]

The goal is to filter schemaArr based on the table_name and field_name specified in the displayArr. When there is a match, the corresponding description and display_name should be added to the displayArr. For instance:

const displayArr = {
   sections: {
      section_1: [
        {
          style: "single_select_cmp",
          definition: {
            table_name: "table_1",
            field_name: "organization",
            description: "Organization Description", //***
            display_name: "Organization" //***
          }
        },
      ],
      section_2: [
        {
          style: "single_select_cmp",
          definition: {
            table_name: "table_1",
            field_name: "title",
            description: "Title Description", //***
            display_name: "Title" //***
          }
        },
      ]
   }
};

In this scenario, I am focusing only on data from table_1, but there could be multiple tables referenced within displayArr.

Given the nesting of these objects, it presents a more complex mapping and filtering task. I am seeking guidance on how to effectively utilize map, filter, and/or forEach for this purpose.

Thank you for your assistance! Your support is greatly appreciated.

Answer №1

Utilizing Object.values() allows for accessing values within the displayArr object, while forEach() can be implemented to iterate through them.

The find() method is effective in locating a specific table based on its table_name within the schemaArr. If the table is found, another call to find() helps in pinpointing the column associated with the item's field_name.

Subsequently, the definition of the respective item in the displayArr object can be updated with the identified column values.

Object.values(displayArr.sections).forEach(section => {
  section.forEach(item => {
    let table = schemaArr.find(table => table[item.definition.table_name]);

    if (table) {
      // Locate column by field_name.
      let obj = table[item.definition.table_name].columns.find(column => column.field === item.definition.field_name);           

      if (obj) {
        // Update definition attributes.
        item.definition.description = obj.description;
        item.definition.display_name = obj.display_name;
      }
    }
  });
});

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

Unable to retrieve data from response using promise in Angular 2?

I am struggling to extract the desired data from the response. Despite trying various methods, I can't seem to achieve the expected outcome. facebookLogin(): void { this.fb.login() .then((res: LoginResponse) => { this.acce ...

transferring a function from a main component to a nested component using swipeout functionality in react-native

I am attempting to transfer a function from a parent container to a child container within react native. The user is presented with a list of items on the screen, where they can swipe the list to reveal additional options. Child import React from &ap ...

Is there a way for me to come back after all child http requests have finished within a parent http request?

I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player. Due to the structur ...

Looking for a Regex pattern for this example: 12345678/90 MM/DD/YYYY

I am having success with the first 10 digits spaced apart, but unfortunately my date regex is not working as expected. ^(\d{6}\s{2}|\d{8})\/(\d{1}\s|\d{2})\s\/(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))&bso ...

Assistance needed for jQuery functions running too early

Within my click function, I am setting certain flags and then calling two functions. However, I want these two functions to execute sequentially in order after the flags have been set. jQuery("#element").click(function(e){ var op = jQuery("#box" ...

Seeking particular section of online content in an asynchronous manner

Is there a method for asynchronously requesting a specific portion of a web resource (like the initial 100 bytes) using JavaScript? I believed this could be accomplished through XmlHttpRequest by adjusting its Range header. However, if the server utilizes ...

If the Request does not recognize the OAuth key, generate a fresh new key

I am working with a React Native Frontend and an Express.js backend. The backend makes calls to a 3rd party API, which requires providing an OAuth key for the user that expires every 2 hours. Occasionally, when calling the API, I receive a 400 error indi ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

What is the best way to use scrollIntoView() to display an additional item at the top or bottom of the visible area

When implementing scrollIntoView() with navigation buttons (up and down), I aim to display two items at a time to signal to the user that there are more items to navigate. However, the first and last items should retain their default behavior so the user u ...

Modifying the disabled attribute of an input tag upon button click in Angular 2

I am currently working on a function in Angular 2 where I want to toggle the disabled attribute of an input tag upon button click. Right now, I can disable it once but I am looking to make it switch back and forth dynamically. Below is the HTML template c ...

Using Page.ResolveClientUrl in JavaScript or jQuery allows for easy resolution of client

I find myself in a predicament where I need to choose between using an HTML page instead of a .aspx page for performance reasons. Currently, I am using an aspx page solely because of the CSS and javascript file paths like: <script type="text/javascript ...

In the process of attempting to upload a .tsv file through the front end interface, I am encountering a challenge as the file remains stored on my server. What is the

I've got a function set up on my Express server that sends a file dependent on D3.JS. app.get('/dashboard', function(req, res) { var timestamp = utility.timestamp(); console.log('[' + timestamp + '] Request made to rend ...

Can you provide the date time format used in the JSTL fmt tag?

To display date and time in JSTL, the fmt tag can be utilized. Details can be found here In order to format the date for use with front end tools like the datatable, a specific date format needs to be specified. By using parameters such as type or dateSty ...

Using jQuery to dynamically include option groups and options in a select box

Generate option groups and options dynamically using data retrieved via AJAX. <select name="catsndogs"> <optgroup label="Cats"> <option>Tiger</option> <option>Leopard</option> <option>Ly ...

HMR: The webpack-hot-middleware is not refreshing my webpage

My Vue application, titled hello-world, is utilizing webpack-dev-middleware and webpack-hot-middleware. When running the application, it shows that it's connected in the console. However, after making changes to my main.js file, the following message ...

The full execution of Jquery show() does not pause until it finishes

Here is the sequence I want to achieve: Show a div element with the CSS class yellow Execute a function for about 5 seconds Remove the yellow class and add the green CSS class "state Ok" However, when running my code, the div container does not appear u ...

How can I upload a folder with subfolders and keep the structure intact?

I'm working on a form that allows me to upload a folder containing both files and subfolders with more files inside. I managed to upload the folder successfully, but when I check my directory, all the files are in one folder without the subfolders. My ...

Achieving synchronous function execution with a single click in React

In my current project, I am utilizing ReactJs and Redux. I have encountered a scenario where I need to trigger two functions sequentially with just one click on the mainfunc(). The second function should only execute after the first function has complete ...

Issue with scrolling feature in div

I am currently facing an issue with scrolling on my website. Visit this site to see the problem. When scrolling down, it causes the "hidden" part of the site to slide up. I want to achieve a similar sliding effect, but it needs to be smooth. I have attempt ...

How to implement setState within a Promise function using useEffect in React functional components with hooks?

I am struggling to set the value of a hook within a Promise function inside a useEffect(), and then store the returned promise value in the fruit hook so that it can be accessed in the return function of MyComponent() This is what I have attempted so far: ...