How to transform complex JSON into a nodes and links format using JavaScript with various key values

I am looking to transform my JSON array data into a structured tree format. The current JSON data is in the form:

      "data": {
        "name": "Sint Maarten",
        "introduction": {...},
        "geography": {...}
        },

I want to convert it to something like this:

{"nodes":[{"id":'Sint Maarten'},{"id":'Hemisphere'}, {"id": "N"}, {"id":"E"}], "links": [{source:"Sint Maarten", target:"Hemisphere"}, {source:"Hemisphere", target: "N"}, {source: "Hemisphere", target: "E"}]}

My goal is to visualize it as a tree structure, similar to this:

Sint Maarten ---> Hemisphere ---> [N,E]
             ---> Language ---> [Language 1, L2, L3] 

I have attempted manually flattening the JSON object array and adding elements into nodes but I need help with creating the links correctly due to the nested nature of the data. Is there a technique or algorithm to achieve this hierarchical visualization for my dataset?

Any advice on how to approach this problem would be greatly appreciated.

EDIT: Here is my current code snippet:

let rawData = fs.readFileSync('./database/factbook.json')
let picker= JSON.parse(rawData)

let arr= {}
arr['name'] = picker['name']
arr['hemisphere'] = [picker['geography']['geographic_coordinates']['latitude']['hemisphere'], picker['geography']['geographic_coordinates']['longitude']['hemisphere']]
arr['area'] = '/'
...
...

I am trying to create an array with the desired output by selecting specific parameters from the raw file, as it contains many fields but I am only interested in a subset. Once I have this array, I need to organize the key-value pairs into a node-links structure that accounts for arrays within some key values.

key: [a,b,c]

If a key value is an array, the expected output in links should reflect each element of the array.

key --> a
key ---> b
key ---> c

``

Answer №1

Welcome to our platform! Here is a more general solution utilizing object-scan, as the specifics were not provided.

This can serve as a starting point for your needs. If you have any questions, feel free to reach out!

// const lodash = require('lodash');
// const objectScan = require('object-scan');

const data = [{ name: 'Sint Maarten', introduction: { background: '... long text ...' }, geography: { location: '... long text ...', geographic_coordinates: { latitude: { degrees: 18, minutes: 4, hemisphere: 'N' }, longitude: { degrees: 63, minutes: 4, hemisphere: 'W' } } } }];

const convert = (() => {
  const logic = {
    '[*].name': ({ value, context }) => context.nodes.push({ id: value }),
    '[*].geography.geographic_coordinates.{latitude,longitude}.hemisphere': ({ value, parents, context }) => {
      context.nodes.push({ id: 'Hemisphere' });
      context.nodes.push({ id: value });
      context.links.push({ source: parents[parents.length - 2].name, target: 'Hemisphere' });
      context.links.push({ source: 'Hemisphere', target: value });
    }
  };
  return (haystack) => {
    const r = objectScan(Object.keys(logic), {
      breakFn: (kwargs) => {
        kwargs.matchedBy.forEach((needle) => logic[needle](kwargs));
      }
    })(haystack, { nodes: [], links: [] });
    r.nodes = lodash.uniqWith(r.nodes, lodash.isEqual);
    r.links = lodash.uniqWith(r.links, lodash.isEqual);
    return r;
  };
})();

console.log(convert(data));
/* => {
  nodes: [
    { id: 'Hemisphere' },
    { id: 'W' },
    { id: 'N' },
    { id: 'Sint Maarten' }
  ],
  links: [
    { source: 'Sint Maarten', target: 'Hemisphere' },
    { source: 'Hemisphere', target: 'W' },
    { source: 'Hemisphere', target: 'N' }
  ]
}
 */
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e4e7ece9fbe0c8bca6b9bfa6bab8">[email protected]</a>"></script>
<script src="https://bundle.run/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d8d5ddd2d4c39ac4d4d6d9f78684998e9987">[email protected]</a>"></script>

Disclaimer: This message was brought to you by the creator of object-scan

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

Endless scrolling feature malfunctioning

On my profile_page.php, the default setting is to display 10 posts (10 rows from the database) for the user. If a user has more than 10 posts, and scrolls to the bottom of the page, the div should expand to reveal the remaining posts (maximum of 10). For e ...

VueJS Router error: The variable $route is undefined

Check out my component: const Vue = require("vue/dist/vue.js"); const qs = require("querystring"); module.exports = Vue.component("Page",function(resolve){ console.log(pageRoute); let id = pageRoute.params.id; fetch("/getPage.json",{ ...

Retrieving various values with identical paths from JSON files using the JSON map feature in SAS

Could anyone assist me in extracting multiple values from a JSON with the same path using a JSON map? Any assistance would be greatly appreciated. Thank you. JSON { "totalCount": 2, "facets": {}, "content": [ [ { "name": "custo ...

Overflowing issue with jQuery Show DIV disrupting footer of other DIVs

I have utilized jQuery to create a simple show/hide functionality. Currently, I am facing two issues: 1) The hidden DIV is displaying over the footer instead of causing the footer to drop down automatically. How can I achieve this? 2) Is there a way to h ...

configure Next.js to exclude a specific subPath within the host from being processed

I've encountered an issue with my public_html directory where there is a folder named blog that is unrelated to my NextJs app. After deploying the app on the host, everything works fine until I try to access the blog section using the following URL: w ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

Transforming vanilla JavaScript into jQuery

Is there a more efficient way to write this code using jQuery? It's functioning properly in Firefox but not in Safari or Chrome without any error messages, making it difficult for me to troubleshoot. Any suggestions or insights would be greatly appre ...

Conceal the scroll bar while still allowing for scrolling functionality

In this code snippet, I am trying to maintain the scroll position of two blocks by syncing them together. Specifically, I want to hide the scrollbar of the left block while scrolling the right one. If anyone has any suggestions or solutions for achieving ...

The interconnected nature of multiple asynchronous tasks can lead to a render loop when relying on each other, especially when

My asynchronous function fetches data in JSON format from an API, with each subsequent call dependent on the previously returned data. However, there are instances where I receive null values when trying to access data pulled from the API due to the async ...

The act of loading a webpage without inserting any data into the database is not recommended

I've created an enroll.html page with the following code: <HTML> <HEAD> <script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></scr ...

Extract information from Excel files using the js-xlsx library

I am currently utilizing the js-xlsx library. If necessary, you can access my excel sheet here. The code I have implemented is as follows: /* setting up XMLHttpRequest */ var url = "Test.xlsx"; var oReq = new XMLHttpRequest(); oReq.open("GET", url, true); ...

Encountering issues after setting up JSON API in Swift

I have successfully implemented most of the functionality. However, when I build the project and execute the function, it processes the API content before crashing abruptly. Here is the updated code snippet: // // GamesTableViewController.swift // Footb ...

Is Vue js converting nested objects into strings before returning them?

There is an object in my code var user = { name:"test", number:"9666-0503", details:{ test:"cannot_access_this", second_field:"nope_no_go" } } A call to a Vue JS action is being made [TYPES.FETCH_USER]({ ...

At what point is it necessary to generate a new vertex array object when sketching numerous objects?

I'm embarking on a game development project using WebGL. Currently, I have three textures in my arsenal- one for letters used in the font, another for character sprites, and a tilemap texture for the world. With these large textures at hand, I find m ...

Do you know the term for when JavaScript is utilized to display specific sections of a png image?

Imagine you have an image file in the format of a PNG which includes various icons intended for use on a website. How can JavaScript be utilized to choose and showcase a specific icon from that image? It's a technique I've observed in practice, b ...

What are the best techniques for improving keyboard accessibility in website navigation?

I spent a considerable amount of time searching for a multi-level vertical menu with the option to include parent links. Eventually, I came across the navgoco jQuery plugin which I have integrated into my project. I am really impressed with this plugin. Ho ...

What are some ways to make session variables available for sub applications?

I am currently working on setting up an API to interact with a MongoDB database, which I have integrated as a subapplication. In my server controller, I have created a session variable. However, I am facing an issue where the session variables are not be ...

Unit testing is encountering issues due to errors with objects not being accepted as a React child component

Here is the code where I am testing the functionality of mytestFunc when a checkbox is checked. Checkbox - <input id="mycheck" type="checkbox" onClick={this.mytestFunc} /> mytestFunc function - mytestFunc = e => { const mockdata = this.stat ...

"Arranging the categories on the xAxis in highcharts based on total values - a step

Is it possible to sort this highchart chart by total? View the highchart chart here The desired final output would be: Name 1 -> 19 Name 4 -> 12 Name 3 -> 10 Name 2 -> 8 See the code snippet below: $(function () { $('#contain ...

Using an array of JSON objects to set up a Backbone.js bootstrap-initialized application

Trying to bootstrap a backbone collection by using an array of JSON objects has led to some unexpected errors. When attempting to call reset on the collection object, an error from Backbone is thrown - Uncaught TypeError: undefined is not a function. Inte ...