Uncover nested arrays within a flattened map by utilizing annotations

Given the JSON structure below, annotate the nested values accordingly.

{
  '0': '0',
  '1': '1',
  '2-0': '2-0',
  '2-1': '2-1',
  '3-0': '3-0',
  '3-1-0': '3-1-0',
  '3-1-1': '3-1-1',
  '3-2': '3-2'
}

Now, I want to transform this into a nested array as shown below:

[
  '0',
  '1',
  [
    '2-0',
    '2-1'
  ],
  [
    '3-0',
    [
      '3-1-0',
      '3-1-1'
    ],
    '3-2',
]

Any suggestions on how to achieve this transformation?

I prefer using TypeScript (or JavaScript), but welcome solutions in other languages too.

Answer №1

let data = {
    '0': '0',
    '1': '1',
    '2-0': '2-0',
    '2-1': '2-1',
    '3-0': '3-0',
    '3-1-0': '3-1-0',
    '3-1-1': '3-1-1',
    '3-2': '3-2'
}

let output = Object.keys(data).map(key => ({
            key,
            value: data[key]
        })).reduce((accum, item) => {
            let keys = item.value.split("-");
            let last = accum;
            keys.forEach((key, index) => {
                if (index === keys.length - 1) {
                    last[key] = item.value;
                } else {
                    if (!last[key]) {
                        last[key] = [];
                    }
                }
                last = last[key];
            });
            return accum;
        }, []);

console.log(output);

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

Creating a new array by elegantly extracting elements from an existing array

I'm trying to improve the efficiency and flexibility of constructing the array final_array_transpose using elements from another array, imb_data (which currently contains 5 elements but could potentially have any number). The code snippet below shows ...

Loop through and display content on the webpage with a for loop

I'm attempting to create a loop that will display information in three different areas of the DOM. Essentially, I have an array of enemies and I want to randomly select three of them to display in separate HTML div classes (firstEnemy, secondEnemy, th ...

Issue with const declaration in Typescript and Node.js - initializer is missing

Encountering a syntax error with the following line of code. Error message: SyntaxError: Missing initializer in const declaration const dataMap : Map<string, any> = new Map(); ...

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

Searching for a subsequence within a text using C programming language

Perhaps I've been approaching this problem in the wrong way. While learning some Javascript, I created a program that detects a specific string within another string and stores the matches in an array. However, when attempting to replicate this progra ...

Troubleshooting Issue with Angular Library: Live Reload Feature Not Functioning

In setting up my Angular workspace, I have 3 libraries and one application (with more to be added in the future). This is how the TypeScript paths are configured: "paths": { "@lib/a/*": [ "projects/libs/a/*", ...

Using C++ C99, transferring information from an array to a vector

Currently, I am working with two classes that handle communication data. In one of the classes, the information is stored in a fixed array like this: uint8 msg[512]; // This fixed array helps reduce memory fragmentation on the target Now, I need to me ...

How can I add a subdocument to a MongoDB array based on a specific condition being met?

When pushing sub documents into an array, the structure of the subdocs typically looks like this: { id:"someId", date:Date } The goal is to only add a new subdoc if there isn't already another subdoc with a matching id. The $addToSet modifier in ...

Exploring the distinction between "() => void" and "() => {}" in programming

Exploring TS types, I defined the following: type type1 = () => {} type type2 = () => void Then, I created variables using these types: const customType1: type1 = () => { } const customType2: type2 = () => { } The issue surfaced as "Type ...

Encountering an error code TS5055 when attempting to call an API within a TypeScript constructor

I'm attempting to retrieve a list of customers by calling a GET API from a dashboard constructor as shown below: // tslint:disable-next-line:max-line-length constructor(public addCustomerDialog: MatDialog, private router: Router, private rout ...

Sequenced: A succession of X items

I'm seeking assistance with creating a linq query that can determine if the list contains x consecutive objects when arranged by date. For example: myList.InARow(x => x.Correct, 3) This query should return true if there are 3 consecutive objects ...

Steps for preloading a user prior to the page loading

Main Concern I currently have an Auth Provider set up in my application that wraps around the entire _app.tsx file. This allows me to utilize the "useAuth" hook and access the user object from any part of the app. However, I am facing an issue when using ...

Error: Unable to locate module with associated type definitions when utilizing Typescript in Next.js

Currently, I am working on a next.js project that I'm attempting to integrate typescript into. The structure of my folders is organized as follows: api aggregation.ts interfaces index.ts components Component1 index.js index.module.css ...

Utilizing ng-repeat $index for locating an element within an array

Within my $scope, there is a property called $scope.cars, which is an array of cars. Users have the ability to delete a car from this array. When calling the delete function deleteThis, I pass the $index parameter created by ng-repeat. However, in the Ja ...

struggling to set default values for route parameters in Angular

I'm struggling with setting default values for my route parameters within the ts class of my component. I would like genreId to default to null, while monetization, sortBy, and page should have preset values. I'm unsure whether I should handle th ...

Angular = encountering an incorrect array size limitation

I am encountering an issue with the function in my controller... $scope.pagerPages = function (n) { var i = Math.ceil(n); return new Array(i); } The n value is derived from an expression on the view and can sometimes be a fraction. This is why I ...

What is the best way to filter out only empty elements in an array using PHP?

In PHP, I have an array and I am looking to only keep blank values within the array. How can I achieve this? Here is the structure of my array: $array = array(0=>5,1=>6,2=>7,3=>'',4=>''); After filtering, the resulting ...

What is the reason behind TypeScript treating numbers as strings when adding them together?

Although TypeScript is strongly typed, can you explain why the code below outputs 12 instead of 3? function add_numbers(a: number, b: number){ return a + b; } var a = '1'; var b = 2; var result = add_numbers(<number><any>a, b) ...

What is the proper way to send a List of Strings containing key=value pairs to an Object?

As a newcomer to JavaScript, I am seeking a more efficient method for converting a list string into an object. The service provides me with the following list, but I require it in object form for processing purposes. For example: let objString = ['n ...