Using JavaScript to plot JSON information on a map

Currently, I have a JSON dataset that needs to be reformatted into a different structure.

This is the original JSON data:

{
  "info": {
    "file1": {
      "book1": {
        "lines": {
          "102:0": [
            "102:0"
          ],
          "105:4": [
            "106:4"
          ],
          "106:4": [
            "107:1",
            "108:1"
          ]
        }
      }
    }
  }
}

The desired mapping looks like this:

{
  "name": "main",
  "children": [
    {
      "name": "file1",
      "children": [
        {
          "name": "book1",
          "group": "1",
          "lines": [
            "102",
            "102"
          ],
          [
            "105",
            "106"
          ],
          [
            "106",
            "107",
            "108"
          ]
        }
      ],
      "group": 1,

    }
  ],
  "group": 0
}

However, I anticipate having more files and books in the future. In the lines section, the first part (before the colon) between quotes is extracted ("106:4" becomes "106"). The number from the key comes first, followed by numbers from the corresponding values forming a list (["106", "107", "108"]). The group information relies on parent-child relationships where the first level parent is group 0 and so forth. The initial name ("main") is also user-defined.

So far, I have attempted the following code snippet:

function build(data) {
    return Object.entries(data).reduce((r, [key, value], idx) => {
      //const obj = {}
      const obj = {
        name: 'main',
        children: [],
        group: 0,
        lines: []
      }

      if (key !== 'reduced control flow') {
        obj.name = key;
        obj.children = build(value)
          if(!(key.includes(":")))
          obj.group = idx + 1;
      } else {
        if (!obj.lines) obj.lines = [];
        Object.entries(value).forEach(([k, v]) => {
          obj.lines.push([k, ...v].map(e => e.split(':').shift()))
        })
      }

      r.push(obj)
      return r;
    }, [])
  }

  const result = build(data);
  console.log(result);

The issue lies in the generation of correct group information. I am currently exploring ways to resolve this problem and would greatly appreciate any assistance you can offer.

Answer №1

One way to construct the nested structure is by utilizing the reduce method along with a recursive function.

const data = {"info":{"file1":{"book1":{"lines":{"102:0":["102:0"],"105:4":["106:4"],"106:4":["107:1","108:1"]}}}}}

function build(data) {
  return Object.entries(data).reduce((r, [key, value]) => {
    const obj = {}

    if (key !== 'lines') {
      obj.name = key;
      obj.children = build(value)
    } else {
      if (!obj.lines) obj.lines = [];
      Object.entries(value).forEach(([k, v]) => {
        obj.lines.push([k, ...v].map(e => e.split(':').shift()))
      })
    }

    r.push(obj)
    return r;
  }, [])
}

const result = build(data);
console.log(result);

Answer №2

The concept of the group property eludes me, so perhaps more information on that could provide clarity. However, to achieve your desired result, you can experiment with these two functions that recursively transform an object.

var a = {"info":{"file1":{"book1":{"lines":{"102:0":["102:0"],"105:4":["106:4"],"106:4":["107:1","108:1"]}}}}};

var transform = function (o) {
    return Object.keys(o)
            .map((k) => { 
                  return {"name": k, "children": (k === "lines" ? parseLines(o[k]) : transform(o[k])) } 
              }
            )
}

var parseLines = function (lines) {
    return Object.keys(lines)
            .map(v => [v.split(':')[0], ...(lines[v].map(l => l.split(":")[0]))])
}

console.log(JSON.stringify(transform(a)[0], null, 2));

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

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Django REST Framework Bulk PUT (Update)

After implementing viewsets and routers, I have created an API that successfully returns specific fields. However, I am facing an issue where I can only update (PUT) ONE detail in the JSON at a time. My goal is to update all details simultaneously. Within ...

Using Vue.js for instant field validation when sending PHP post forms for enhanced user experience

A unique approach is being taken to utilize vue.js exclusively for real-time field validation, while the form will ultimately be submitted using PHP through the POST method. However, a challenge arises where vue.js takes control of the form, hindering PHP& ...

Steps for concealing a specific field in StrongLoop's outcome

Currently, I am working on a project using strongloop to develop a web service for user login. While my code is functioning properly and producing the desired output, the issue lies in the fact that it does not hide the password. The result I am receiving ...

Can we pass a search term parameter to getServerSideProps in Next.js?

I've been working on a project to organize all my notes and summaries in one place. The notes are stored as markdown files, converted to HTML dynamically in the backend (it's functioning well). Now, I want to add a search feature on the notes p ...

Creating multiple JSON files using a for loop and outputting only the last line of the table

I encountered an issue with the csv data extracted using web crawling. Specifically, after utilizing the "Equipment" column of the csv data for prop.value, my goal is to generate JSON files for each row. This requires creating multiple json files through a ...

How can I use a dropdown with checkbox to toggle the visibility of a specific div in React?

I have come across a relevant question, but I am struggling to apply it to multiple divs. I haven't found a solution that quite fits my needs. Show or hide element in React Currently, I am using the dropdown with checkboxes from MUI. I am seeking a ...

What is the best way to direct users to the individual product page once they make a selection

On my main products page, I am fetching all the products from a local JSON file. interface productItem { id: number; name: string; image: string; price?: string; prices: { half: string; full: string; }; ...

Using JSON.stringify() for custom serialization of an object

Imagine there is an object called a with properties: const a = { foo: 123, bar: 'example' } Now, this object is a part of another object called b like this: const b = { a: a, anotherField: "example" } While working with TypeScript, th ...

Displaying JSON data in a popup window resembling a download prompt

I'm a beginner in front end development and facing difficulty in displaying JSON in a new window. Currently, I'm allowing users to download the JSON file like this var blob = new Blob([$scope.data], {type: 'json'}); ...

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

The modification of Javascript content type occurring following URL Rewrite

I'm currently working on setting up a Reverse Proxy with ARR and URL rewrite in order to achieve the following redirection: Source: http://localhost/test Destination: http://localhost:83/ The goal is for the final URL displayed to be same as the so ...

How can I replicate the design of the d3.js homepage?

Is there any available information on the d3.js homepage regarding how they create the interactive hexagons? I am interested in replicating this effect with a set of photos where the tiles move slightly and highlight when hovered over. You can visit for ...

Having trouble with RethinkDB filter not returning any matches?

Encountering an obstacle with RethinkDB while using NodeJS. Attempting to utilize a basic .filter() function, but for some mysterious reason, it fails to retrieve a result. The current code snippet in question looks like this: const someID = 1234; ...

Fixing the Material UI upgrade error: "Make sure you have the right loader for this file type."

As a beginner in React, Webpack, Babel, and web development, I have been tasked by my company to upgrade the material-ui version for a dropdown search component. The current version used in the project is "1.0.0-beta.43", and I decided to start by upgradin ...

Implementing the sticky class once the user scrolls past a certain element

I am facing an issue in my vue component where I need to add a fixed class to an element when the user scrolls past it. However, the sticky console.log seems to be firing on every scroll instead of only when the element is passed. I also want to remove the ...

What causes the discrepancy in CSS behavior between local and remote websites?

My chrome extension enhances facebook chatbox with jquery autocompletion. I am trying to make the suggestion list menu horizontal by modifying the jquery-ui.css. When changing display:block to display:inline, the list becomes horizontal in a local HTML fil ...

Adding images to HTML using JavaScript below existing images

I'm currently working on a JavaScript game and I want to implement a feature where my character can move under blocks (isometric PNG images) instead of just sliding through them. Is there a way to dynamically adjust my character's position in the ...

Using Gulp Filter in Conjunction with Source Maps

My initial query was similar to this one here, but it led me to delve deeper into research and explore a new approach. Essentially, I am attempting to consolidate all my .js and .coffee files within a single gulp.src() object and execute relevant tasks ba ...

Generating a collection of items using php

Transform array of items into a list of objects using PHP: [ Object { id=0, label="Myriel", group=1 }, Object { id=1, label="Napoleon", group=1}, .... .... ...