Reorganize the format of a JSON data structure

I am in the process of creating numerous JSON files for a project, sourced from Google Spreadsheets. By utilizing data-drive npm package, I acquire JSON data that has a specific structure:

{
  "custom_id": 1,
  "another_thing": "pizza",
  "step_1_message": "msg",
  "step_1_hint": "hint",
  "step_1_intent": "intent",
  "step_2_message": "msg",
  "step_2_hint": "hint",
  "step_2_intent": "intent"
}

However, I aim to restructure the data so that each step is encapsulated within its own object. The desired format would be:

{
  "custom_id": 1,
  "another_thing": "pizza",
  "steps": [
   {"step_id": 1, "message": "msg", hint: "hint", "intent": "intent"},
   {"step_id": 2, "message": "msg", hint: "hint", "intent": "intent"}
  ]
}

Answer №1

Below is the effective solution:

let inputData = {
  "custom_id": 1,
  "another_thing": "pizza",
  "step_1_message": "msg",
  "step_1_hint": "hint",
  "step_1_intent": "intent",
  "step_2_message": "msg",
  "step_2_hint": "hint",
  "step_2_intent": "intent"
};
let outputData = {
    steps: []
};
for (let key in inputData) {
    let match = key.match(/step_([0-9]+)_(\w+)/);
    if (match) {
        let stepNum = match[1];
        let name = match[2];
        if (!outputData.steps[stepNum - 1]) {
            outputData.steps[stepNum - 1] = {
                step_id: stepNum
            };
        }
        outputData.steps[stepNum - 1][name] = inputData[key];
    } else {
        outputData[key] = inputData[key];
    }
}

Answer №2

It has a touch of Perl inspiration.

A strategy to follow is to compare each key-value pair against a regular expression pattern that matches keys containing "step". Subsequently, extract these key-value pairs and iterate through them to find additional details like messages, hints, etc. These values can then be used as inputs for constructing your Object. To accommodate jsons with varying numbers of key-value pairs, you will need a flexible constructor within the class definition of your objects.

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

Retrieve a string value in Next.JS without using quotation marks

Using .send rather than .json solved the problem, thank you I have an API in next.js and I need a response without Quote Marks. Currently, the response in the browser includes "value", but I only want value. This is my current endpoint: export ...

The execution of the Mocha test script is hindered by a socket.io issue causing it to

Running my tests (mocha) by typing npm run test in the console was working fine until I pulled down some code from my team. There seems to be an issue now. We are building an app that utilizes Socket.io, and for some reason, it appears in the command promp ...

I am facing an issue with ThreeJs where my objects are not getting rendered after being added to a

After refactoring some code, I encountered an issue where nothing was being displayed. Surprisingly, there were no errors in the console to guide me towards a solution. The code in question is supposed to generate the same output as a previously functionin ...

What is the optimal method for sending an error response to an Ajax request?

After I call a WebMethod using ajax and return a simple string, the success method of the ajax code is executed without any errors. Here's an example: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string Hello() { ...

The FOSJsRoutingBundle is unable to detect a route coming from the FOSRESTBundle

I am facing an issue with accessing an API route to a FOSRESTBundle Controller from my JS. Even though I am using the FOSJSRoutingBundle, the route is not visible, and I keep getting the 'the route xxx does not exist' error. The following is an ...

Is it possible to access the grid in ASP.NET Kendoui through code?

When trying to access my grid from Javascript code, I seem to have made mistakes. Can you help me locate them? This is the Grid code I am using: <div id="kendoo"> @(Html.Kendo().Grid<SalePortal.ServiceReference.Product>() .Name("Grid") .Col ...

The DropDownList does not automatically refill with the previous selection after a page refresh

I'm encountering an issue with my HTML website where the second DropDownList is not being populated when I refresh the page or go back from a redirected page. How can I fix this? You can check out the problem I'm facing at GiveToTheYToday.org if ...

Is it possible to link an HTML select element to a changing array in JavaScript?

Let's say I have an empty HTML select element. <select id="options"> </select> Can I link a JavaScript array to this select so that when the array is modified, the select options update accordingly? Alternatively, do I need to resort to ...

Discover a keyword located within particular markers

let find_word="xyz" let el=document.getElementById("text"); let arr = el.innerHTML.split(" "); let newarr=[]; for (let i = 0; i < arr.length; i++) { if (arr[i] === find_word) { n ...

Laravel's join method does not play well with toArray functions

Everything is running smoothly with the current code. No issues with toArray $restaurants = Restorant::where(['active'=>1])->orderBy('id', 'desc')->limit(10)->get(); $data = []; $item = []; foreach ...

How can we optimize the organization of nodes in a group?

While many questions focus on grouping nodes based on similarity, I am interested in grouping nodes simply based on their proximity. I have a vast collection of densely packed nodes, potentially numbering in the millions. These nodes take up space on-scre ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

Unlocking the Secret: Retrieving Click Event Values from a jQuery Function

Is there a way to retrieve the onclick event value change in jQuery when clicking on a DIV? $("ul li").click(function(){ var newValue = $(this).val(); }); $(function(){ alert(newValue); }); ...

Creating a jQuery AJAX form that allows users to upload an image, submit the form, and store the entered values in a MySQL database

I am struggling with an HTML form that I am trying to submit using jQuery's $.ajax(); The form needs to: 1. Upload an image to a directory with error checks 2. Save the image path to a MySQL database 3. Insert two other form values (input and select) ...

Utilizing Javascript's every() method to verify if all elements in an array are integers

I am currently working on a function that needs to return true if an array contains all integers, and false if it does not. I am incorporating the every method for this purpose, which is documented on MDN here. For example, if the input is '1234&apos ...

My Tailwind CSS toggle button disappears in dark mode, why is that happening?

<button aria-label="Toggle Dark Mode" type="button" className="lg:inline-flex lg:w-40 md:w-screen p-3 h-12 w-12 order-2 md:order-3" onClick={() => setTheme(theme === 'dark' ? &ap ...

Making an HTTP request using Kotlin in an Android application

I attempted to retrieve JSON data or something similar by using URL.readText() from java.net.url in Android Studio, but my application crashes. fun ButtonClick(view:View) { textView.text = URL("https://www.google.com/robots.txt").readText() } ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

Unlimited scrolling with jQuery/Ajax

I am currently working on implementing infinite scroll functionality using ajax, php, and mysql in my web application. However, I am facing difficulty in loading new content only when the user reaches the end of the page. Currently, all the data is loaded ...

What steps need to be taken in order to print the validated HTML form?

My online food ordering form has a validation issue where the content does not display on the screen after submission. I found a workaround by changing the type of the "submit" button from an input to a button. However, is there a way to print the content ...