JavaScript is utilized to flatten nested JSON objects into a single level of arrays or objects

I am currently attempting to flatten a json object with multiple embedded levels, here is an example of the original structure:

[
    {
        "one": 1,
        "two": 2,
        "three": [
            {
                "four": 4,
                "five": 5
            },
            {
                "six": 6,
                "seven": 7
            }
        ]
    },
    {
        "one": 1,
        "two": 2
    }
]

My goal is to transform it into this desired result:

{
    "0": {
        "prefix[0]one": 1,
        "prefix[0]three[0]five": 5,
        "prefix[0]three[0]four": 4,
        "prefix[0]three[1]seven": 7,
        "prefix[0]three[1]six": 6,
        "prefix[0]two": 2
    },
    "1": {
        "prefix[1]one": 1,
        "prefix[1]two": 2
    }
}

I have found a script that successfully flattens the data, but I am looking for a way to group each top level array/object separately rather than combining them all into one large object.

The current code snippet I have been working on is below:

JSON.flatten = function(data) {
    var result = {};
    function recurse (cur, prop) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
             for(var i=0, l=cur.length; i<l; i++)
                 recurse(cur[i], prop + "[" + i + "]");
            if (l == 0)
                result[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop+p : p);
            }
            if (isEmpty && prop)
                result[prop] = {};
        }
    }
    recurse(data, "prefix");
    return result;
}

The output of the current code snippet looks like this:

{
    "prefix[0]one": 1,
    "prefix[0]three[0]five": 5,
    "prefix[0]three[0]four": 4,
    "prefix[0]three[1]seven": 7,
    "prefix[0]three[1]six": 6,
    "prefix[0]two": 2,
    "prefix[1]one": 1,
    "prefix[1]two": 2
}

In an update, I realized my desired output should be structured differently, like so:

{
    "0": {
        "prefix[0][one]": 1,
        "prefix[0][three][0][five]": 5,
        "prefix[0][three][0][four]": 4,
        "prefix[0][three][1][seven]": 7,
        "prefix[0][three][1][six]": 6,
        "prefix[0][two]": 2
    },
    "1": {
        "prefix[1][one]": 1,
        "prefix[1][two]": 2
    }
}

After further exploration, I discovered that this new format would not fully work due to the nested objects. To address this, I am following suggestions from other developers and adopting a recursive approach to assign values as needed. Thank you for your input!

Answer №1

Why bother modifying the flatten function when it already fulfills its purpose? Instead of tweaking the function, consider formatting the flattened output to suit your specific requirements.

function customFormat(obj, prefix){

    var result = {};

    for (var key in obj) {  

        var newKey = key.replace(prefix + "[", "").split("]")[0];

        if(!result[newKey]){
            result[newKey] = {};
        }

        result[newKey][key] = obj[key];
    }

    return result;
}

You can then use it as follows:

console.log( customFormat(JSON.flatten(yourData), "prefix") );

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

What are some ways to create a flashing effect for text in HTML and JavaScript?

Although flashing text is typically prohibited in many places, my client has requested it for a project. I need to create one line of text that flashes using HTML and JavaScript. The text should appear and disappear within seconds, repeating this cycle. I ...

What is the best way to unpack a JSON string from a GET request in Django?

It seems like there's a glaringly obvious problem that I just can't seem to spot. When using ipython (Python 2.7), the following code works fine: In [1]: json.loads('[]') Out[1]: [] Now, I'm attempting to replicate this simple e ...

Tips for updating React context provider state when a button is clicked

WebContext.js import React, { createContext, Component } from 'react'; export const WebContext = createContext(); class WebContextProvider extends Component { state = { inputAmount: 1, }; render() { return <WebC ...

"Implementing drag and drop functionality in Vue.js without the need for a

Exploring html 5 drag and drop functionality using vue js has been a challenging experience for me. After following the w3schools tutorial on drag and drop, I managed to get it working in a basic html file but faced difficulties when implementing it in my ...

Stop the background from being visible using the jQuery Cycle plugin

I'm facing a challenge with the cycle plugin for jquery when creating a slideshow. The transition between slides allows what's underneath to show, but I want a smoother transition where one slide truly fades into the other without the background ...

The webpage is completely blank, displaying only a stark white screen

After designing a website, I encountered an issue where upon opening it in the browser, it only shows a blank white page. I am puzzled as to why this is happening. Could you please take a look at this link and assist me? Thank you in advance. ...

Modify content on a link using AngularJS

Currently, my setup looks like this: HTML Code <div ng-app="home" ng-controller="customersCtrl"> <div ng-bind-html="home" id="content">{{content}}</div> </div> JS Code angular.module('home', []).controller('c ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

What is the best way to adjust the height and width of an mp4 video in Internet Explorer?

I came across a code snippet that looks like this video { object-fit:fill; } <!DOCTYPE html> <html> <body> <video width="800" height="240" controls> <source src="http://www.w3schools.com/tags/movie.mp4" type="video/mp4" ...

Elusive shadow fails to appear in ThreeJS scene

<style> body { margin: 0; } </style> <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0267712f6f6d66776e672f716a6a6f716a6f717a333c343c71">[email protec ...

Using dot notation for JSON serialization, including arrays

I need help converting a dot-notation string to a JSONObject while also including arrays. For example, I want to assign first.second[0].third[0].fourth to some string. The resulting JSON should look like this: { "first": { "second": [ { ...

Tips for preventing the parent component from rerendering in React.js

My question involves the ProductList component, which serves as the parent component. Within the render method of this component, I have written the following code: return ( <div> <CustomBreadCrumbs routes={this.props.routes} ...

Express server unable to process Fetch POST request body

I'm currently developing a React app and I've configured a basic Express API to store user details in the database app.post("/register", jsonParser, (req, res) => { console.log("body is ", req.body); let { usern ...

Issue with displaying selected value and options in Mat-select when using formarray - Reactive forms in Angular

I've been working on the code below to create dropdowns, but I'm having trouble getting the selected value and options to show up in the dropdowns. Can you help me figure out what's wrong with the code? Component code testForm: FormGroup; ...

I'm attempting to insert a line break after HTML elements that are being added from JavaScript code inside a `display: flex` div

I'm facing an issue where line breaks are not added after HTML elements are inserted via JavaScript upon clicking a button. For instance, the data from the inputs doesn't get separated even when I click submit multiple times: https://i.sstatic. ...

Disabling the onClick event on HTML tags with personalized WooCommerce messages

I have customized the notices/success.php template file by modifying the content as shown below: <?php foreach ( $messages as $message ) : ?> <div class="woocommerce-message" role="alert"> <span> <?php ...

How to manage rejections in async/await within the Array#map method

In my Node 8.1.2 project, I encountered a scenario where one file is calling another file's function within a map structure. While in a real example, I would normally use Promise.all on the map, that specific implementation is not the focus of this qu ...

The issue is that the Push() function is not functioning properly when it is invoked from within

I am currently incorporating the jQuery drag and drop formbuilder plugin into my project. My goal now is to retrieve drag and drop elements from my database and integrate them into the drag and drop builder. Here is the function I am using for this reques ...

I'm puzzled as to why my recursive function is repeatedly calling itself without meeting the necessary logical condition. Can anyone provide guidance on

As I delve into a basic recursion, I am observing an interesting phenomenon where the logic governing the recursion is activated even when a false parameter is present in the return statement for the ternary rule. This particular recursive function perfor ...

Developing a jsp page with interconnected drop down menus

I am looking to dynamically populate the options in a second drop-down based on the selection made in the first drop-down. For instance, if I have a first drop-down with options {India, South Africa, USA}, and I choose India, then the second drop-down shou ...