JavaScript Recursive Function for Generating FancyTree JSON Structure

I'm currently building an array of JSON objects for FancyTree (https://github.com/mar10/fancytree/wiki/TutorialLoadData). My JSON source is from the Jira REST service, and its structure can vary widely. Therefore, the code to construct the array of JSON objects needs to be adaptable and capable of handling any format.

Below is an example of the source JSON:

{
"feed": {
    "entry": [
        {
            // Json content omitted for brevity
        }
    ]
}
}

The challenge is to transform this data into a specific format as shown below:

[
{title: "Node 1", key: "1"},
{title: "Folder 2", key: "2", folder: true, children: [
  {title: "Node 2.1", key: "3", myOwnAttr: "abc"},
  {title: "Node 2.2", key: "4"},
  {title: "Folder 3", key: "5", folder: true, children: [
    {title: "Node 3.1", key: "6", myOwnAttr: "xyz"},
    {title: "Node 3.2", key: "7"}
  ]}
]}
]

While attempting to achieve this transformation, I've encountered some difficulties with the current implementation. Any assistance or suggestions on improving the logic would be greatly appreciated. Thank you!

Answer №1

A more concise code solution could be:

const createMenu = (obj) =>
  Object .entries (obj) .flatMap (([k, v]) =>
    Array .isArray (v)
      ? []
    : Object (v) === v
      ? [{title: k, folder: true, children: createMenu (v)}]
      : [{key: k, title: `${k}`, tooltip: v}]
  )

const convertData = (obj) =>
  obj .feed .entry .map ((o) => ({
    title: 'Item',
    folder: true, 
    children: createMenu (o)
  }))

const dataInput = {feed: {entry: ... INSERT YOUR DATA HERE ...}}

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

In this implementation, createMenu is responsible for the recursive actions, while convertData wraps it for root level handling.

By utilizing flatMap and transforming single returns with arrays, we can efficiently process arrays in properties without cluttering the code. This approach merges functionalities of filter and map.

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

VueJS Array Index causing unexpected output

I have been developing a unique poetry application that pulls in poetry using an API call. To fetch the data, I am utilizing the axios library and using v-for to render the data. The index from v-for is used to load the image for each respective poem. My ...

React's constructor being invoked twice

As a newcomer to react, I am in the process of developing a simple web application but encountering an issue. It seems like my Constructor is being called twice when I load a class component. Can anyone provide some assistance? Home.js import React from ...

Loop through a collection of arrays that contain the same elements, and multiply each consecutive element by a specified value x

I've been diving into a challenging problem involving remarkable numbers, which are defined as A number that is equal to the sum of all its proper divisors -- provided one of them is negative. For instance, the proper divisors of 12 are 1, 2, 3, 4, 6 ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

Accept JSON data within a node server utilizing express

I am encountering an issue with sending a JSON object to my node server in Java. I am trying to display the value in the server console but it is showing up as "undefined." Can someone provide guidance on how to properly retrieve the JSON object and parse ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

What is the best way to store an ES6 Map in local storage or another location for later use?

let map = new Map([[ 'a', 1 ]]); map.get('a') // 1 let storageData = JSON.stringify(map); // Saving in localStorage. // Later: let restoredMap = JSON.parse(storageData); restoredMap.get('a') // TypeError: undefined is not a ...

Updating the state within a component while specifically modifying the second item within a list

Currently in the process of constructing a battleShip game using React. Within my component, I have a state structured as follows: each coordinate is paired with a list containing two statuses - 'empty' indicating the absence of a ship ('bu ...

Upon successfully logging in via an API, I received a JSON response. Now, I want to display the length of the arrays as the count for my notification icon. Any suggestions on how I can

I have implemented the following code to fetch JSON data in my app. The JSON response includes user details and notifications. { "user_id": 1, "user_name": "Mr Admin", "api_token": "6S3gRnPy55JKWyiOF7SwtYO12waZ8 ...

displaying a Google Map within a designated container

I'm currently working on a basic website layout that consists of a full-width banner, a left menu (200px), and right content (600px). I have a simple jQuery script set up to load the content on the right-hand side when any of the five menu items are c ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

Vue.js transition-group does not apply the *-move class

As I dive into learning Vue, I find myself wondering if I may have overlooked something fundamental or stumbled upon a bug. Despite multiple readings of the documentation at https://v2.vuejs.org/v2/guide/transitions.html#List-Move-Transitions, I still can& ...

Modifying the content in one form field based on the information entered in another input field

I have a scheduling application that includes a form for selecting both the departure city and arrival city. The app is designed for international travel only, so when a user selects a city from Hungary as the departure city, I want to exclude all Hungaria ...

Javascript Using Promise to Await Ajax Content Loading

As a newcomer to JavaScript, I am exploring ways to traverse a DOM that utilizes Checkboxes for filtering results and displays them through Ajax. The checkboxes are organized in 4 levels: Grand Parent Parent Child Grand Child My goal is ...

The 'else' statement does not seem to function properly with the 'src' attribute

I have been attempting to include alt text in a web page using jQuery with the code below. However, I am only able to get the correct value for the first image. The else if and else conditions do not seem to be working properly as I am unable to add alt ...

The integration of Firebase Google Auth seems to encounter issues when used on the Vercel

My experience with Vercel deployment has been quite interesting. While I find that Google authentication works seamlessly on localhost, it seems to encounter an issue when deployed on Vercel. Specifically, after logging out, the currentUser variable always ...

JsTree throws an error stating that the JSON is invalid

I am in the process of creating a Jstree and here is the code for it: $(function () { $("#groups") .jstree({ "plugins" : [ "themes", "json_data", "ui", "crrm", "cookies", "dnd", "search", "types", "contextmenu" ], "json_data" : { ...

Issues with displaying AngularJs directive template

Having an issue with my AngularJs directive. Everything works perfectly fine when I use the "template" attribute, but when I switch to using "templateURL", it stops working. Both the JavaScript file for the directive and the HTML file for the template are ...

Exploring the process of navigating through jQuery Arrays: Utilizing JQuery Array Filter

I need help finding a way to SEARCH through a jQuery array or object. I'm not looking to just check if the value is in the array, but to search for related terms based on user input. It's similar to how we filter ArrayList in Java or use SQL LIKE ...