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

Error: Module not found '!raw-loader!@types/lodash/common/array.d.ts' or its type declarations are missing

I encountered a typescript error while building my NEXT JS application. The error message was: Type error: Cannot find module '!raw-loader!@types/lodash/common/array.d.ts' Below is the content of my tsConfig.json file: { "compilerOptions& ...

After the upgrade from Angular 5.2 to Angular 6, Bootstrap 4 dropdown and Bootstrap-select dropdown seem to have lost their dropdown functionality. This issue arose after updating to Bootstrap 4 and jquery

Update: Upon further investigation, I experimented with a standard Bootstrap 4 dropdown and encountered the same issue – it would not open. This leads me to believe that the problem may not be specific to the selectpicker class or the bootstrap-select de ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Adjusting the OrbitControl target in a React environment

I attempted to create a model using react-three-fiber and react-drei, but the OrbitControl target setting is causing it to appear too high. import React, { useRef, useState, Suspense, useEffect } from 'react' import { Canvas, useFrame, useLoader, ...

Determine image size (pre-upload)

One of the requirements for a project I am working on is to verify the dimensions (width and height) of images before uploading them. I have outlined 3 key checkpoints: 1. If the dimensions are less than 600 X 600 pixels, the upload should be rejected. ...

What is the best way to pass the setState value to the useEffect hook?

After watching a Youtube video, I took on the challenge of creating my own recipe app using React.js as a beginner. I have been troubleshooting for the past 2 days and seem to have hit a roadblock. The issue lies in passing the value of my state to the use ...

What is the best way to remove an active item from a Vue v-list?

When using Vuetify's v-list-item directive, I encountered an issue where the active prop cannot be removed once an item has been selected. Here is my approach so far: <v-list-item-group pb-6 color="primary" class="pb-3 text-left"> ...

Best Practices for Implementing JSON.stringify() with an AJAX Request

While I have a limited understanding of ajax and JSON, I am aware that using JSON.stringify in an ajax call can sometimes be beneficial. The ajax call below is functioning properly, whereas the one following it with the stringify method is not. I am unsure ...

Parent function variable cannot be updated within a $.ajax call

I'm facing an issue with pushing a value from inside an ajax call to an array located outside of the call but still within the parent function. It appears that I am unable to access or update any variable from inside the ajax success statement. Any as ...

Utilizing Vue CLI's sourcemaps to pinpoint the styling within a Vue component file

Currently, I am working on a Vue CLI project. After setting up the project and making some development changes, my package.json file now includes: package.json "dependencies": { "bootstrap": "^4.3.1", "core-js": "^3.0.1", "preload-it": "^1.2. ...

A fixed header for tables that shifts along with horizontal scrolling

Seeking assistance with a persistent issue - I have a table with a fixed header on vertical scroll (see CSS and Javascript below), but the header fails to move horizontally when I scroll. window.onscroll = functi ...

Having trouble accessing the ng-model within ng-repeat in the controller of an AngularJS component

One approach I am considering is to use ng-model="model.ind[$index]" in order to keep track of the active tag. This way, when I click on a tag (specifically the 'a' tag), both the parentIndex and $index will be passed to my controller. Subsequent ...

Where to Locate a String Excluding <a> Tags?

I'm in the process of writing a JavaScript code that will scan an HTML document and identify all occurrences of a specific keyword that are NOT contained within a link, meaning not under an <a> tag. To illustrate this, let's examine the fol ...

Discovering the Voice Channel of a User using Discord.js v13

I'm currently working on a 'wake up' command for my bot that should move the mentioned member between 2 specific voice chats and then return them to their original VC. I've successfully got the bot to move me between those 2 VCs, but no ...

Provide alternative styling through css in instances where the Google Books API does not provide an image

How can I modify the CSS code to display the author and title of a book when there is no image available from the Google Books API? Currently, users see a custom image linked here, but it's not clear what it represents without the name and author inf ...

Obtaining the variable from the exec function in Node.js can be achieved by capturing

I am trying to access the values of variables w1 and h1 outside of the exec function and display them using console.log. exec(command, function(err, stdout, stderr) { var resolution = stdout.split("x"); w1 = resolution[0]; h1 = resolution[1]; ...

Utilizing jQuery to implement a function on every individual row within a table

I have a collection of objects that requires applying a function to each item, along with logging the corresponding name and id. Below is the snippet of my code: var userJson = [ { id: 1, name: "Jon", age: 20 }, { ...

Troubleshooting Problems with POST Requests in ExpressJS

Currently, I am working on developing a feature in NodeJS that allows users to upload files. However, I am encountering difficulties while attempting to make a simple POST request. In my index.ejs file, I have written code that generates a form and initia ...

Reinvent the AJAX functionality

Is there a way to create a custom function that changes the default ajax functionality? I currently have this ajax function implemented: $.ajax({ type: "POST", url: "http://" + document.location.host + '/userajax', data: 'type= ...

"Placing drop-down animations in just the right spot

I'm currently working on adjusting the dropdown behavior for thumbnails when hovering over them. I want the drop-down to appear beneath the 'Caption Title' instead of above the image, but so far my CSS adjustments haven't been successfu ...