Transforming the structure of a JSON file using javascript

What is the most efficient and quickest method to convert a JSON object named 'from' into another one called 'to'? Can this conversion be done in a single step, or should duplicates be handled first?


const from =[{ 
    NUM: '1234001',
    SUBNUM: '001'},
  { 
    NUM: '1234001',
    SUBNUM: '001'},
  { 
    NUM: '1234002',
    SUBNUM: '002'},
  { 
    NUM: '1234005',
    SUBNUM: '005'},
  { 
    NUM: '4567001',
    SUBNUM: '001'},
  { 
    NUM: '9999001',
    SUBNUM: '001'}
];


const to = [{
  label: 'SUBNUM',
  submenu: [{
    label: '1234',
    role: '1234',
       submenu: [{
         label: '001',
         role: '001'
       },
       {
         label: '002',
         role: '002'
       },
       {
         label: '005',
         role: '005'
       }]
    },{
    label: '4567',
    role: '4567',
       submenu: [{
         label: '001',
         role: '001'
       }]
    },{
    label: '9999',
    role: '9999',
       submenu: [{
         label: '001',
         role: '001'
       }]
  }
  ]}];

Answer №1

If you're looking for a solution, you can experiment with the code below:

const elements = [];

from.forEach(obj => {
    let truncatedNumber = obj.NUM.replace(obj.SUBNUM, "");
    let currentNumber = elements.find(n => n.label === truncatedNumber);
    if(!currentNumber) {
        currentNumber = {
            label: truncatedNumber,
            role: truncatedNumber,
            submenu: []
        };
        elements.push(currentNumber);
    }

    if(!currentNumber.submenu.find(item => item.label === obj.SUBNUM)) {
        currentNumber.submenu.push({ label: obj.SUBNUM, role: obj.SUBNUM });
    }
});

let result = { label: "SUBNUM", submenu: elements };

The find method will return undefined if there is no element that matches the specified arrow function. Additionally, use the replace method from the string prototype to remove instances of SUBNUM.

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

Searching for unique values in MongoDB using a distinct query on the MongoLab

I am currently working with database XXX and collection YYY in MongoDB, hosted on MongoLab. Below is an example of a sample record: { "_id": { "$oid": "551a5asdfsdfsdfs" }, "_class": "com.test.com", "mvid": "d0fffsdfs" } My goal is to retrieve ...

Best Practices for Managing Arrays of Various Objects in Angular 9 HTTP Requests

As a newcomer to Angular and web development, I apologize in advance if my terminology or explanations are not accurate. Here is my issue: I am working with Angular 9 and making http requests (get and post) to an API using the HttpModule. The response ob ...

Android refuses to launch Google Play links from JavaScript in web applications

My HTML app is wrapped in Phonegap and available on the Android store. I want to include a link within the app for users to update it if a new version is available. From what I've gathered from documentation and some Stack Overflow posts, the follow ...

Exploring Filtering, Slicing, and Sorting Techniques with Angular Factory in JavaScript

I am currently working on generating a filtered, sorted, and sliced list of data items in my Angular application. After successfully sorting and slicing the data, I encountered an issue when using dataHandler.filter. The error message 'Cannot read pro ...

Getting an image from a JSON response and showcasing it in a collection view in iOS

I'm a newcomer to iOS and I need help displaying an image URL from JSON on a collection view. Below is the code I've been using, but I'm having trouble getting the image to display. Can anyone assist me with this? // Collection View Code - ...

Save the outcome of an ArrayBuffer variable into an array within a Javascript code

I'm in the process of developing an offline music player using the HTML5 FileReader and File API, complete with a basic playlist feature. One challenge I'm facing is how to store multiple selected files as an ArrayBuffer into a regular array for ...

Attempting to dynamically change the reference when resizing in React.js

Encountering a small issue here. My goal is to have a reference on a viewport and use that value to determine the number of rows to display in a table at a time. I was able to successfully retrieve the value: number. However, I need this value to update w ...

Strategies for temporarily storing values within md-list-item in AngularJS

I am attempting to populate a list with items using material icons. The issue is that the values are being added permanently when the material icon is clicked, disregarding the save and discard buttons at the bottom of the card. My goal is to add values te ...

How to grasp this particular date within nodeJS?

Can anyone help me properly format this date 2018-11-04T14:00:00-07:00? I obtained it from the NWS API but I've had trouble using Date() and similar functions. ...

Issues with Jquery on Internet Explorer 7

CSS Design: <div id="overlay_weekPrize"> <div class="prizePopupBanner"> </div> <div id="weeklyPrizeImageBanner"><!--the large banner images/weeklyPrizeImageBanner--> <div id="week1"><img src="images/b ...

Troubleshooting: JQuery is not properly adding the CSS value

I have a piece of code that adds a CSS class to an element once the user scrolls to a specific point on the page. This is intended to create a sticky menu bar. The distance to scroll is determined based on the screen resolution and is calculated using JQue ...

Adding a KendoColorPicker to a column in a Kendo Grid

When using AngularJS with a Kendo UI grid, I need to have a column that includes a colorPicker. Below is the code I have implemented: $scope.thingsOptions = { sortable: "true", scrollable: "true", toolbar: [{ name: "create", text: "Add Profile ...

Show complete items in Vue.js

Issue at hand: I am in need of displaying and potentially changing JSON data. My goal is to present it in a directory tree format. The structure of the object is unknown, it could be something like this: "buttons": { "login": "LOGIN", "register": ...

Assistance needed for upgrading database features

Currently, I'm developing a back-end feature for a client that involves the ability to add new records and modify existing ones using a simple interface. Despite making progress, I've hit a roadblock and realize my initial approach may not have b ...

Vue - Syntax error: Unexpected token, expecting "}."

I recently started working with Vue and have encountered a simple component issue. Sometimes, when I run npm run serve or save a file that is already being served, I receive the following error message: E:\Development\website\app>npm run ...

A basic problem involving appending content using jQuery

I have encountered a puzzling issue. Whenever I attempt to insert new content into the <div> element using my JS code, it briefly appears and then disappears abruptly. I am unsure of the reason behind this behavior. Is there a way to prevent this fr ...

Take away the focus from Bootstrap 5 toggle button once it has been clicked

Working with the Bootstrap 5 Toggle Button in Outline Style to enhance visual emphasis hasn't provided the ideal user experience I was hoping for. (Refer to https://getbootstrap.com/docs/5.0/forms/checks-radios/#outlined-styles) The toggle functional ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

Prevent computed observables from being included in server data by using KnockoutJS

While working on this project, I came across a helpful section in that discusses "Determining if a property is a computed observable." In order to achieve this, I utilized the isComputed function to validate whether a property is indeed a computed observa ...

The cursor is located on the right side instead of the usual left side

Why is the cursor positioned on the right side rather than the left side? $('.legoact').focus(); When the cursor is positioned on the right side, it can be achieved using the following CSS properties: .lego{ background:#ddd; width:70%; m ...