Converting a TypeScript nested dictionary into a list of strings

I am currently working with a nested dictionary and my goal is to convert it into a list of strings. For example, the initial input looks like this:

var group = {
    '5': {
        '1': {
            '1': [1, 2, 3],
            '2': [1]
        },
        '2':{
            '1': [2, 4],
            '2': [1]
        }
    },
    '1': {
        '1':{
            '1':[1, 2, 5],
            '2':[1]
        },
        '2':{
            '1':[2, 3]
        }
    }
};

The desired output should be:

a = ["5.1.1.1", "5.1.1.2", "5.1.1.3"..... "1.2.1.3"]

To achieve this, I began by creating a recursive function:

function printValues(obj) {
    for (var key in obj) {
    console.log(key)
        if (typeof obj[key] === "object") {
            printValues(obj[key]);   
        } else {
            console.log(obj[key]);    
        }
    }
}

However, the function is not producing the expected result yet..

Answer №1

To tackle this problem, one effective approach is to combine iterative and recursive methods to extract the most deeply nested items first and construct the desired strings.

What is the underlying process?

This method involves iterating through an object's key/value pairs and appending a spreaded array to the final result set.

The spreading array can either be

  • an array of values or

  • an array obtained by recursively calling the function with the object v as input

Both arrays are then mapped using the object's key k and an element from the associated array to generate the desired style n.m.

For instance, consider a sub-object { 1: [2, 4], 2: [1] } and retrieve an array of key/values.

[
    [1, [2, 4]],
    [2, [1]]
]

This represents the outcome after the initial stage of reduce. The sequence follows the logical flow starting from the innermost level:

  1. Identify it as an array,
  2. Fetch v with [2, 4],
  3. Map this value along with k 1,
  4. Obtain array of ['1.2', '1.4'],
  5. Spread this array and
  6. Append each element as parameter.

Proceed to the subsequent iteration and fetch ['1.2', '1.4', '2.1']. This output serves as the value extracted by getPathes and linked with the current key in front of each string.

The end result is achieved via a depth-first search to access the deepest internal array and prepend the key before each item.

function getPathes(object) {
    return Object.entries(object).reduce((r, [k, v]) => {
        r.push(...(Array.isArray(v) ? v : getPathes(v)).map(l => `${k}.${l}`));
        return r;
    }, []);
}

var group = { 5: { 1: { 1: [1, 2, 3], 2: [1] }, 2: { 1: [2, 4], 2: [1] } }, 1: { 1: { 1: [1, 2, 5], 2: [1] }, 2: { 1: [2, 3] } } },
    result = getPathes(group);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you need to traverse through nested objects and arrays, you can implement a recursive function using Object.entries:

var data = {
    '5': {
        '1': {
            '1': [1,2,3],
            '2': [1]
        },
        '2':{
            '1': [2,4],
            '2': [1]
        }
    },
    '1': {
        '1':{
            '1':[1,2,5],
            '2':[1]
        },
        '2':{
            '1':[2,3]
        }
    }
};

let result = []
const extractPaths = (path, value) => {
  if (Array.isArray(value)) {
    value.forEach(item => result.push([...path, item].join('.')))
  } else {
    Object.entries(value).forEach(([key, value]) => extractPaths([...path, key], value))
  }
}

extractPaths([], data)
console.log(result)

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

How about adjusting this RPG Battle Sequence?

Both the client and server sides of my game are built in JavaScript. I have opted not to implement a master game loop since combat is infrequent and nothing else in the game requires one. When two players engage in combat, they enter an auto-attack loop as ...

Attempting to single out various entities within a JSON array through the use of radio buttons

I am currently developing a website to showcase sports teams' schedules. Each team has its own JSON file containing relevant information that I aim to display upon selecting the team from a radio button. For instance, let's consider the example ...

Dynamic value updates using jQuery input type formulas

I need help with a form that has two inputs: The first input allows the user to enter an amount, such as 1000. The second input is read-only and should display the value of the first input plus 1%. For example, if the user types in 1000 in the first fie ...

What are the steps to set up mocha to automatically monitor source or project files?

Is there a way for Mocha to only watch my source/project files and not the test files? The test files and source/project files are located in separate directories. Any help or guidance would be greatly appreciated. Thank you! ...

``There appears to be an issue with the functionality of the jQuery

I've been experimenting with using AJAX in a PHP form, but for some reason it's not working as expected. I'm at a loss trying to figure out why. Here is my code: <!DOCTYPE html> <html lang="es"> <head> <title>< ...

Server requests are being redirected to /index.html in order to load the React/Angular SPA

Imagine having a React or Angular application hosted at www.mywebsite.com/index.html with Apache as the server. The app includes various routes like /aboutus or /faq, even though there are no individual files for each route (/aboutus.html or /faq.html). Th ...

Duplicate user scrolling input within a specified div container

I am attempting to recreate a horizontal scrolling effect on a div element that mirrors the input scroll. When the user scrolls along the input, I want the div element to scroll in sync. The issue I am encountering is specific to Chrome, where the input b ...

Angular: Unable to access values of non-existent data (reading '0')

I'm encountering an error when trying to import an excel file using the following code Angular Ag Grid Excel Import Cannot read properties of undefined (reading '0') I'm attempting to import a file named Book.csv, and wondering if thi ...

Filtering strings with the same suffix

Here is a code snippet I am working with: type RouterQuery = keyof AppRouter['_def']['queries']; This code defines the following type: type RouterQuery = "healthz" | "post.all" | "post.byId" | "catego ...

Exploring methods to successfully upload a blob to Firebase and modify it using cloud functions

For days now, I've been attempting to successfully upload a file to firestorage using firebase functions but haven't had any luck. This is the progress I've made so far: export const tester = functions.https.onRequest(async (request, respons ...

Unexpected outcome when returning a map

Encountered a puzzling issue that requires immediate clarification. When I input the following code into my project: this.metadata = json.metadata.map((x) => {return new Metadatum(x);}); console.log(this.metadata[0].value); The output consistently sho ...

Searching and Sorting through JSON Data in React Native

I am currently expanding my knowledge in React Native and experimenting with filtering a JSON data set on a screen. My goal is to display only the filtered results on the screen. Would it be advisable for me to create a new component called FilteredTicket? ...

Updating the content within a div following the submission of a contact form 7

I'm struggling with my contact form. I want the content of my contact form div to change after clicking submit on the form. I've been searching for a solution, but so far, no luck. Here is what I have: Form (div1) with input fields, acceptance c ...

How can I design a Typescript interface that accommodates both strings and other data types?

I am working on designing an interface that allows for an array of objects and strings to be stored. For instance: const array = [ '', {id: '', labels: ['']} ] I attempted to achieve this using the following code: export ...

How to Display Prices in Euros Currency with Angular Filter

Can someone help me figure out how to display a price in euros without any fractions and with a dot every 3 digits? For example, I want the price 12350.30 to be shown as 12.350 €. I attempted to use the currency filter but it only worked for USD. Then ...

What are the steps to resolve the UglifyJs error stating 'Unexpected token operator'?

When running the following command in my Angular app: > ng build --prod --aot --env=staging I encounter this error message: ERROR in vendor.0625f773941bc83e6748.bundle.js from UglifyJs Unexpected token operator «*», expected punc «(» [vendor.0625 ...

Exploring the @HostBinding argument in Angular directives

Need help grasping the concept behind the @Hostbinding argument: Snippet of the code: import { Directive, HostBinding } from "@angular/core"; @Directive({ selector: '[appDropdown]' }) export class DropdownDirective { @HostBinding(&apos ...

Display four unique automobile insignias using Webcomponent/Stencil.js

Exploring Web Components and Stencil.js for the first time, I'm currently developing an application that offers detailed car information based on the user's selection of car type. The challenge I'm facing involves displaying four different l ...

The CORS policy has blocked access to XMLHttpRequest at 'https://saja.smjd.ir/api/Account/login' from the specified origin 'http://**'

I have successfully completed my project using Angular 9 on the frontend and asp.net core 3 on the backend, and deployed it to a server. However, I am facing an issue when trying to obtain or use a token from the server. Access to XMLHttpRequest at 'h ...

Implement a feature to dynamically load data as the user scrolls up, similar to the

I am in the process of creating a messaging platform and I am looking to implement a functionality where chat history is displayed upon scrolling up, similar to Facebook's chat system. Can anyone offer assistance with this task? ...