Reorganizing JSON structures by incorporating unique identifiers into nested elements

I am working on restructuring an incoming JSON object to utilize in a React component.

The JSON data that I'm receiving is stored in jsonData. This is the current structure of my code:

const jsonData = {
  "Jonas": {
    "position": "CTO",
    "employees": [{
      "Sophie": {
        "position": "VP Engineering",
        "employees": [{
            "Nick": {
              "position": "Team Lead",
              "employees": [{
                  "Pete": {
                    "position": "Backend Engineer",
                    "employees": []
                  }
                },
                {
                  "Barbara": {
                    "position": "Fronted Engineer",
                    "employees": []
                  }
                }
              ]
            }
          },
          {
            "Melissa": {
              "position": "Product Manager",
              "employees": []
            }
          }
        ]
      }
    }]
  }
}

const userList = [jsonData]

const formatData = list =>
  list.map(item => {
    let name, position, employees
    for (let key in item) {
      name = key
      position = item[key].position
      employees = item[key].employees ? item[key].employees : []
    }

    return {
      name,
      position,
      employees: employees ? formatData(employees) : employees
    }
  })

console.log(formatData(userList))

I am attempting to assign a new id to each object and transform the jsonData into an array. The desired output should include the following -

[
  {
    "id": 0,
    "name": "Jonas",
    "position": "CTO",
    "employees": [
      {
        "id": 1,
        "name": "Sophie",
        "position": "VP Engineering",
        "employees": [
          {
            "id": 2,
            "name": "Nick",
            "position": "Team Lead",
            "employees": [
              {
                "id": 3,
                "name": "Pete",
                "position": "Backend Engineer",
                "employees": []
              },
              {
                "id": 4,
                "name": "Barbara",
                "position": "Frontend Engineer",
                "employees": []
              }
            ]
          },
          {
            "id": 5,
            "name": "Melissa",
            "position": "Product Manager",
            "employees": []
          }
        ]
      }
    ]
  }
]

How can I incorporate an id for each object in the generated output?

Answer №1

If you're looking to transform data using JavaScript, one approach is to utilize Object.assign along with a closure that maintains a counter for the unique identifiers.

function processData(input) {
    const processItem = obj => (name => Object.assign(
        { id: id++, name },
        obj[name],
        { children: obj[name].children.map(processItem)
    }))(Object.keys(obj)[0]);

    var id = 0;
    return processItem(input);
}

var initialData = { Alice: { role: "Manager", children: [{ Bob: { role: "Developer", children: [{ Charlie: { role: "Designer", children: [] } }] }, { Diana: { role: "Marketer", children: [] } }] } };
var processedResult = processData(initialData);

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

Answer №2

One way to dynamically generate IDs is by creating a variable called id and incrementing it inside a loop.

const jsonData = {
  "Jonas": {
    "position": "CTO",
    "employees": [{
      "Sophie": {
        "position": "VP Engineering",
        "employees": [{
            "Nick": {
              "position": "Team Lead",
              "employees": [{
                  "Pete": {
                    "position": "Backend Engineer",
                    "employees": []
                  }
                },
                {
                  "Barbara": {
                    "position": "Fronted Engineer",
                    "employees": []
                  }
                }
              ]
            }
          },
          {
            "Melissa": {
              "position": "Product Manager",
              "employees": []
            }
          }
        ]
      }
    }]
  }
}

const userList = [jsonData]
var id=-1;
const formatData = list =>
  list.map(item => {
    let name, position, employees
    for (let key in item) {
      name = key
      position = item[key].position
      employees = item[key].employees ? item[key].employees : []
    }
   id=id+1;
    return {
      id,
      name,
      position,
      employees: employees ? formatData(employees) : employees
    }
     
  })

console.log(formatData(userList))

Answer №3

This method offers a more efficient and organized approach to handling nested arrays of employees.

const companyData = {
  "CEO": {
    "name": "Alice",
    "employees": [{
      "CTO": {
        "name": "Bob",
        "employees": [{
          "Team Lead": {
            "name": "Charlie",
            "employees": [{
              "Developer": {
                "name": "David",
                "employees": []
              }
            },
            {
              "Designer": {
                "name": "Eve",
                "employees": []
              }
            }
            ]
          }
        },
        {
          "Product Manager": {
            "name": "Frank",
            "employees": []
          }
        }
        ]
      }
    }]
  }
}

const employeeList = [companyData]

const reformatData = list => {

  updateEmployeeIds(list, 0, list.length)
  return list
}

const updateEmployeeIds = (item, count, parentNumber) => {
  if (item && Array.isArray(item)) {
    item.map((value, index) => {
      updateEmployeeIds(value, count + index, item.length)
    })
  } else if (item) {
    Object.keys(item).map(key => {
      let value = item[key]
      item.id = count
      item.name = key
      if (value.name) {
        item.name = value.name
      }
      if (value.employees) {
        item.employees = value.employees
      }
      delete item[key]
      if (item.employees) {
        updateEmployeeIds(item.employees, count + parentNumber)
      }
    })
  }
}

console.log(reformatData(employeeList))

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

Fetching various data from MongoDB using NodeJS and presenting it in Jade(Pug) template

I am working with MongoDB collections and need to showcase them on my website, creating a dynamic page that updates automatically. Specifically, I am dealing with team members' information in the database. Here is an example of how my collections loo ...

Having trouble turning off a multi-select drop down option

Hello, I'm a newcomer to AngularJs and facing an issue with disabling my multiselect dropdown under a specific condition. Initially, I attempted to disable the dropdown using the following code: document.getElementById("multidropdown").disabled = tr ...

Problem with Safari: File downloaded with name "Unknown" due to Javascript issue

After successfully converting my data to text/csv, I can easily download the file in Chrome. However, when attempting to do so in Safari on an iPad or Mac, it opens a tab with the name "unknown" or "Untitled". The code snippet I am using for this is as fol ...

Retrieving the link to share for every video located in the Dropbox folder

My Dropbox folder contains a set of videos labeled "v1.avi, v2.avi, ....., vn.avi". I am looking to automate the process of extracting the share link for each video in the folder so that I can easily use it as a source value for HTML video. . . . Is ther ...

Stop the event propagation when the back button is clicked

While utilizing ons-navigator, I am looking to customize the function of a particular element at a certain stage. Employing the onClick handler has allowed me to successfully trigger this function. However, upon exiting the onClick handler, the navigator ...

OBJ Raycasting in Three.js

Greetings! I encountered an issue while working with three.js in my project. Specifically, I was trying to select a custom mesh that I loaded from an OBJ file. To troubleshoot, I set up a simple raycaster, a cube, and my custom model (which is also a cube ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

What could be causing the npm install command to not save packages in the /node_modules directory?

After running npm install to add a package, npm indicates that the installation was successful. However, upon checking the node_modules folder, I'm unable to locate the installed package. In order to access the package, I have resorted to using npm in ...

Functionality of jQuery Mobile Page

$(document).on("pageshow", "#mappage", function (event) { $("#doldur").append("<li> <label onclick='getBina(" + featuressokak[f].attributes.SOKAKID + ");'>" ...

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

When adding files through drag and drop, the FormData is including a blank file field in the sent

I am currently working on a photo upload page that has drag and drop functionality enabled. Below is the form code: <form id="Upload" method="post" action="sessionapi/UserPicture/Upload" enctype="multipart/form-data"> <input class="box__file ...

What are the pros and cons of using a piped connection for Puppeteer instead of a websocket?

When it comes to connecting Puppeteer to the browser, you have two options: using a websocket (default) or a pipe. puppeteer.launch({ pipe: true }); What distinguishes these approaches? What are the benefits and drawbacks of each method? How do I know wh ...

JavaScript => Compare elements in an array based on their respective dates

I have an array consisting of more than 50 objects. This array is created by concatenating two arrays together. Each object in this array contains a 'date' key with the date string formatted as: `"2017-03-31T11:30:00.000Z"` Additionally, there ...

The Java Optional class can be used to handle null JSON fields

Utilizing JsonNode objects from the Jackson library to handle json responses, the input could be structured as follows: { "a": "test", "b": true } However, there are instances where the b field might be absent, resulting in a structure like this: ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

What is the best way to handle AJAX or XHR post requests in ExpressJs when JSON data is passed from the front-end to the back-end?

scenario: -> Front-end: jquery handling ajax requests -> Back-end: nodejs, expressjs (v.3.4.8). I am attempting to create a basic contact form. Here is my front-end code: var name = $('#name').val(); var email = $('#email').v ...

What are the advantages of polymer's inter-component data binding?

I am working on a login component and I want to ensure that the login status is accessible by other components within my application. Is there anyone who can share some functional code snippets or examples? I require a method for binding or event handlin ...

Dawn Break Alarm Timepiece - Online Platform

My buddy recently purchased a "sunrise alarm clock" that gradually brightens to mimic a sunrise and make waking up easier. I had the thought of replicating this effect with my laptop, but I've been facing issues with getting the JavaScript time funct ...

Tips for creating a personalized dialog box after logging in with React Admin based on the server's response

One of my requirements is to allow users to select a role during the login process. Once the user enters their username and password, the server will respond with the list of available roles. How can I implement a dialog where the user can choose a role fr ...

"Experiencing a problem with Next.js 13 where the User Context is not functioning properly outside of _app

When using Next.js 13 and the user context, I've noticed that it doesn't function properly outside of _app.tsx. Any idea why? src>context>UserPositionContext.tsx import { createContext, useContext, useState } from "react"; const ...