Tips for utilizing field mapping for a nested item in TypeScript

I am working with two separate objects below,

let response = {
                offer: {
                    custom_fields: {
                        job_title: 'engineer'
                    },
                    starts_at: 'test',
                    job_post: 'test'
                }
            }

let defaultFieldMapping = {
                "$.engagementData.title": {
                    default: "Software Engineer",
                    path: "$.offer.custom_fields.job_title",
                    fieldName: 'Title'
                },
                "$.engagementData.startDateUTC": {
                    default: null,
                    path: "$.offer.starts_at",
                },
            }

I need to create a new object with the following expected result

let expectedResult = [
                {
                    externalFieldId: '$.offer.custom_fields.job_title',
                    integrationFieldId: '$.engagementData.title'
                },
                {
                    externalFieldId: '$.offer.starts_at',
                    integrationFieldId: '$.engagementData.startDateUTC'
                },
                {
                    externalFieldId: '$.offer.job_post',
                    integrationFieldId: ''
                },
            ]

The integrationFieldId is left as an empty string because it does not exist in the defaultFieldMapping path column.

Answer №1

function findNestedKeys(object) {
  function* _findNestedKeys(object, prefix) {
    for (let [key, value] of Object.entries(object)) {
      if (typeof value === 'object' && value) yield* _findNestedKeys(value, `${prefix}${key}.`)
      else yield `${prefix}${key}`
    }
  }
  return [..._findNestedKeys(object, '$.')];
}

console.clear()
console.log(findNestedKeys(response))
console.log(
  findNestedKeys(response)
    .map(innerKey => ({
      innerKey,
      outerKey: Object.entries(defaultFieldMapping).find(([key, value]) => value.path === innerKey)?.[0]
    }))
)

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

Consider yourself a module for npm, just like a node

I'm currently working on a Javascript project that has been released as a node module. In some parts of the source code, I have used relative paths to import other files within the project: // <this_module_path>/action/foo.js import execution f ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

Utilizing Redux with React to fetch and handle JSON data from given API endpoint

The assignment I'm working on requires us to fetch JSON data from a specific endpoint called url and display it in an Excel-like table using React, Redux, and Redux-Thunk. I successfully managed to retrieve and display the data in a table by utilizin ...

Encountering the "React Hook useEffect missing dependency" warning for a state variable that does not actually need to be included in the dependency array

My eslint is throwing an error for react-hooks/exhaustive-deps. I believe my code is correct as the function should only execute when there is a change in the pathname: const pathname = usePathname(); useEffect(() => { setNavigation( navig ...

The Angular project seems to be experiencing technical difficulties following a recent update and is

Recently, I made the transition from Angular 6 to 8 and encountered two warnings during the project build process that I can't seem to resolve. Despite searching online for solutions, nothing has worked so far. Any help would be greatly appreciated. ...

Asynchronous execution of Angular 2 services

Currently, I am working on a project that utilizes Angular and RxJS. My approach involves creating an injectable class responsible for fetching data from a JSON source as shown below: import {Injectable, Inject} from '@angular/core'; import {Ht ...

Events in the backbone view fail to trigger after a re-render

For some reason, I am struggling to get mouse events to work on my backbone view after it is re-rendered. It seems like the only solution is to use a rather convoluted jQuery statement: $("a").die().unbind().live("mousedown",this.switchtabs); I initially ...

The Express.js server seems to be having trouble rendering a static JavaScript file

Currently, I am in the process of constructing a website and have implemented an express.js server to collect data submitted through a form. Prior to configuring the server, I had already developed the site using static js and css files. Once the connectio ...

The function applyMiddleware in React Redux is not working correctly

After thoroughly reviewing my code, I couldn't find any flaws, yet I received this error message: Uncaught TypeError: (0 , _reactRedux.applyMiddleware) is not a function import { applyMiddleware, createStore } from 'react-redux' impor ...

Remove an item from an array within Express using Mongoose

{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee94 ...

Expand Bootstrap accordion on hover

I have tried several examples that I discovered on Google and Stack Overflow, but none of them seem to work. So, I decided to attempt a different solution for opening the Bootstrap accordion on hover, however, it is not working as expected. Do you have any ...

Error message TS2339: The method 'findAll' is not defined in the current context

Despite following the Sequelize guide for TypeScript configuration, I am unable to resolve an issue with my database connection. The connection is active, but I am struggling with a specific type problem: TSError: ⨯ Unable to compile TypeScript: controll ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Testing the GET method in an Angular service: A guide

I'm currently facing an issue with my service method and unit test setup. Despite writing a unit test for the getter method, the coverage report indicates that this method is not covered. I would appreciate any advice on what might be going wrong in m ...

What is the best way to reposition an element to the end of its flexbox container?

I have a flexbox-container that contains multiple details-elements with flex-wrap behavior. My goal is to have a details-element move below the other elements within the container when it is opened. For example, I want it to go from this initial layout: ...

Navigational bar with React and Next.js. Issue: Hydration unsuccessful due to inconsistencies between the initial UI and the server-rendered content

I am working on a project with Next.js and React. I've created a navbar component but I keep encountering the following error message multiple times: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warni ...

Styling of checkboxes in jQuery Mobile is missing after an AJAX request

I am currently working on implementing an ajax call to retrieve a list of items from a json array and display them as checkboxes. While the items are loading correctly, they lack the jquery mobile styling. $(document).ready(function(){ ...

Utilize ramda.js to pair an identifier key with values from a nested array of objects

I am currently working on a task that involves manipulating an array of nested objects and arrays to calculate a total score for each identifier and store it in a new object. The JSON data I have is structured as follows: { "AllData" : [ { "c ...

Challenges in Ensuring Proper Alignment of Connection Line Between Boxes on Left and Right Sides within a React Component

Currently, I am developing a React component that displays two sets of boxes on the left and right sides of the screen. Users can choose one box from each side and click a "Connect" button to draw a line between them. However, I am encountering an issue wh ...

The value of 'Boolean' cannot be changed as it is a constant or a read-only property and cannot be assigned

I've been working on creating a TypeScript object to handle read/write permissions in my application, but I'm stuck on an issue with variable assignment that doesn't make sense to me. Any help or guidance would be greatly appreciated. expor ...