From transforming nested JSON into flat JSON structures within Javascript

Currently, I am faced with a challenge in my JavaScript programming. The task at hand is to transform the JSON data obtained from an API into a different structure while maintaining the essence of the original JSON. The existing JSON comprises members, numerous 'parents' (nested objects), and various children (nested arrays of objects). My goal is to convert these parents into individual members.

An excerpt of the JSON dataset looks like this:

[
    {
        "street": [
            {
                "addressinfo": {
                    "id": 110,
                    "description": "Bezoekaddress"
                },
                "id": 1,
                "name": "Hoogveldstraat"
            }
        ],
        "id": 1,
        "searchName": "JacksIcecream",
        "chamberOfCommerce": ""
    },
    {
        "street": [],
        "id": 2,
        "searchName": "OAK",
        "chamberOfCommerce": ""
    }
]

The desired transformation outcome should resemble the following format:

[
    {
        "street": [
            {
                "addressinfo_id": 110,
                "addressinfo_description": "Bezoekaddress",
                "id": 1,
                "name": "Hoogveldstraat"
            }
        ],
        "id": 1,
        "searchName": "JacksIcecream",
        "chamberOfCommerce": ""
    },
    {
        "street": [],
        "id": 2,
        "searchName": "OAK",
        "chamberOfCommerce": ""
    }
]

I have been grappling with this issue for a considerable amount of time now but have not been able to find a suitable solution. Most discussions I come across focus on flattening arrays, whereas my requirement is centered around 'flattening non-array-nested objects'. How can I go about achieving this particular transformation?

Answer №1

function analyzeData(data) {
    var index, path, value, dataType = ({}).toString.call(data);
    if (dataType == "[object Array]") {
        for (index = 0; index < data.length; index++) {
            analyzeData(data[index]);
        }
    }
    else if (dataType == "[object Object]") {
        path = (arguments[1] && arguments[1].length) ? arguments[1] + "_" : "";
        for(index in data) {
            if (data.hasOwnProperty(index)) {
                value = data[index];
                if (path.length) {
                    delete data[index];
                    data[path + index] = value;
                }
                analyzeData(value, path + index);
            }
        }
    }
}

tested using the code below:

var sampleData = [{
    "street": [{
        "addressinfo": {
            "id": 110,
            "description": "Bezoekaddress"
        },
        "id": 1,
        "name": "Hoogveldstraat"
    }],
    "id": 1,
    "searchName": "JacksIcecream",
    "chamberOfCommerce": ""
}, {
    "street": [],
    "id": 2,
    "searchName": "OAK",
    "chamberOfCommerce": ""
}];
analyzeData(sampleData);
console.log(JSON.stringify(sampleData));

Output (formatted through ):

[{
    "street": [{
        "addressinfo": {
            "addressinfo_id": 110,
            "addressinfo_description": "Bezoekaddress"
        },
        "id": 1,
        "name": "Hoogveldstraat"
    }],
    "id": 1,
    "searchName": "JacksIcecream",
    "chamberOfCommerce": ""
}, {
    "street": [],
    "id": 2,
    "searchName": "OAK",
    "chamberOfCommerce": ""
}]

Answer №2

Iterate through the elements within the main array, locate the street sub-array in each element, and iterate through its elements to modify their values:

data . forEach(function(item) {
  item.street . forEach(function(location) {
    location.addressinfo_id = location.addressinfo.id;
    location.addressinfo_desc = location.addressinfo.desc;
    delete location.addressinfo;
  });
});

Did you have a preference for a more versatile and customizable solution?

Answer №3

Take a look at this

// Changing Nested Json into Flat Json
// View the final json in firebug console.
var fullData = {"data":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road,  West Bengal 734013,  India","Speed":0,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road,  West Bengal 734013,  India","Speed":0,"Children":[]},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58,"Children":[]},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83,"Children":[]},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71,"Children":[]}]};
var finalData = [];
loopJson(fullData.data);
function loopJson(data) {
    $.each(data, function(i, e) {
        if (e.Children.length>0) {
            var ccd = e.Children;
            delete e.Children;
            finalData.push(e);
            loopJson(ccd);
        } else {
            delete e.Children;
            finalData.push(e);
        }
    });
}
console.log(finalData);

Here is the link to access it : http://jsfiddle.net/2nwm43yc/

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

Decoding Nested JSON Structures in C#

Hello everyone, the source I'm referencing is JASON: { "is_error":0, "undefined_fields":["custom"], "version":3, "count":1, "id":15862, "values":{ "15862":{ "id":15862, "contact_type":"Individual", "contact_sub_type":null ...

Customize the background color of MaterialUI KeyboardDateTimePicker without altering the padding and layout of the component

Is it possible to alter the background color of KeyboardDateTimePicker components without affecting the padding and layout? I attempted to set the background property to style={{background: "rgb(232, 241, 250)"}}, but when combined with inputVari ...

What is the best way to eliminate items from an array in a side-scrolling video game?

In my gaming project, I am creating a unique experience where the player needs to collect all the words from a given array. Currently, I am utilizing the shift() method to eliminate elements, as demonstrated in the code snippet below: if ( bX + bird.width ...

Adjust the height of a div based on the font size and number of lines

I'm trying to create a function that automatically sets the height of a div by counting lines. I managed to get it partially working, but then it stopped. Can someone please help me with this? function set_height() { var div_obj=document.getEleme ...

Transmit intricate data structure to a web API endpoint using AJAX requests

When attempting to send a complex object named vm containing an object 'Budget' and an array 'BudgetDetails' populated with rows from an HTML table to my API controller using AJAX, I encounter the error message "Uncaught RangeError: Max ...

When the mouse button is released or when an event listener is

I've been pondering a question that has yet to be fully answered. When I implement this technique to catch a mouse up event: <div onmouseup="/*Script to be executed*/"></div> Is it more efficient than this newer approach: <div id=" ...

Navigating through a JSONObject within another JSONObject

I am trying to send json data, which contains another nested json object. Here is an example: { "key1": "value1", "key2": "value2", "content": { "nestedkey1": "nestedValue1", "nestedkey2": "nestedValue2" } } The nes ...

Tips for executing a function only once within the animation loop in Three.js

Is there a way to call a function only once when a certain condition is met in Three.js? I am currently sampling the frames per second (FPS) to send it to an external service. The FPS is sampled and averaged over time, and the average value is sent after 1 ...

What could be causing the lack of population in ngRepeat?

In my angular application, I encountered an issue with ngRepeat not populating, even though the connected collection contains the correct data. The process involves sending an http get request to a node server to retrieve data, iterating over the server&a ...

Prevent form submission with jQuery during validation process

Currently, I am working on validating a form using jQuery. My main objective now is to have the submit button disabled until all fields are correctly filled in. To achieve this, I have implemented the following approach: http://jsfiddle.net/w57hq430/ < ...

Issue with Heroku: Unable to serve images through NodeJS Express server

I have an app deployed on Heroku that displays an image. app.js package.json package-lock.json public |__ image1.png |__ image2.png This is the code within app.js const express = require('express'); const app = express(); const path = re ...

Building New Web Pages with Express in Node.JS

I want to dynamically generate a new page on Node.JS with Express upon user form submission. Here is my initial approach, but it's not working as expected: var app = require('express')(); var server= require('http').createServer(a ...

AJAX response for form validation

I need to validate my contact form when the submit button is clicked. If all fields are valid, I want to display a Processing message using AJAX, followed by a success message with the entered name. The content of my Form is: <form onsubmit="return va ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

Tips for updating a reactive form with multiple layers of nested JSON values

I am tasked with retrieving and working with the data from a deeply nested (potentially infinite levels) reactive form that includes formArrays, formGroups, and formControls. This data is stored in a database. Currently, my approach involves patching the ...

Exploring Cross Origin Policy Restrictions with Fiddler for JSON Debugging

In the process of creating a modern webapp using JSON data, I came across a helpful blog post about using Fiddler to mock JSON data. My development setup involves working locally with Notepad++ and testing primarily on Chrome, with plans to expand to othe ...

The Laravel Ajax Request is Returning Null

I am faced with a perplexing issue involving a toggle button that should change the status (Show/Hide). Despite sending valid data via ajax and seeing correct data in the console, the request appears empty in the controller. I've made sure to include ...

When attempting to call methods after executing a new Class in Android Studio, the application crashes

I have been working on an app that utilizes JSON data. The issue I am facing is that when I retrieve the JSON using HentData.execute() and assign it to a string variable, my program crashes when I try to perform any operations with it. HentData extends As ...

Angular page not reflecting show/hide changes from checkbox

When the user clicks on the checkbox, I need to hide certain contents. Below is the code snippet: <input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check> To hide content based on the checkbo ...

Validating object keys

I am dealing with an array of objects and I need to find a way to pass multiple keys in the function checkArray to validate these keys within each object. var test = [ { // Object details here... }, { // Another object details here... } ...