A JavaScript function for flattening objects within nested objects and arrays recursively

I have a large JSON object that may be irregular, and I am looking for a solution to flatten all of its objects into a single array.

Here is an example JSON:

{
    "name":"getPost",
    "request":{
        "type":"object",
        "fields":[{
            "key":"id",
            "value":{"type":"string"}
        }]
    },
    "response":{
        "type":"object",
        "fields":[{
            "key":"post",
            "value":{
                "type":"object",
                "fields":[{
                    "key":"id",
                    "value":{"type":"string"}
                },{
                    "key":"title",
                    "value":{"type":"string"}
                },{
                    "key":"content",
                    "value":{"type":"string"}
                },{
                    "key":"userId",
                    "value":{"type":"string"}
                }]
            }
        }]
    },
    "error":[]
}

I would like the output to look something like this: (I only need objects with shallow key-value pairs)

[
    {
        "key":"id",
        "value":{"type":"string"}
    },{
        "key":"post",
        "value":{"type":"object"}
    },{
        "key":"id",
        "value":{"type":"string"}
    },{
        "key":"title",
        "value":{"type":"string"}
    },{
        "key":"content",
        "value":{"type":"string"}
    },{
        "key":"userId",
        "value":{"type":"string"}
    }
]

I am wondering if there is a straightforward way to achieve this without using ES6 features.

Answer №1

This unique approach delves into any data structure by recursively traversing its property key-list to find a matching key provided for collection.

If the keys match, the corresponding (sub)data structure is added to a specified list.

If the (sub)data structure is an array, each data item within it is also processed recursively.

If the (sub)data structure is not of string type, a new recursion loop initiates, as explained in the initial stages of this text.

var data = {
"name": "getPost",
"request": {
"type": "object",
"fields": [{
"key": "id",
"value": {
"type": "string"
}
}]
},
"response": {
"type": "object",
"fields": [{
"key": "post",
"value": {
"type": "object",
"fields": [{
"key": "id",
"value": {
"type": "string"
}
}, {
"key": "title",
"value": {
"type": "string"
}
}, {
"key": "content",
"value": {
"type": "string"
}
}, {
"key": "userId",
"value": {
"type": "string"
}
}]
}
}]
},
"error": []
};


function collectListOfAllSubTypeDataRecursivelyByKey(collector, key) {
  var
    itemKey = collector.key,
    data    = collector.data,
    list    = collector.list;

  if (Array.isArray(data)) {
    data.forEach(function (dataItem) {

      collector.list = list.concat(Object.keys(dataItem).reduce(collectListOfAllSubTypeDataRecursivelyByKey, {

        key:  itemKey,
        data: dataItem,
        list: []

      }).list);
    })
  } else {
    if (key === itemKey) {

      list.push(data);
    }
    if (typeof (data = data[key]) !== 'string') {

      collector.list = list.concat(Object.keys(data).reduce(collectListOfAllSubTypeDataRecursivelyByKey, {

        key:  itemKey,
        data: data,
        list: []

      }).list);
    }

  }
  return collector;
}


var subTypeList = Object.keys(data).reduce(collectListOfAllSubTypeDataRecursivelyByKey, {

  key:  'type',
  data: data,
  list: []

}).list;


subTypeList.forEach(function (type) {
  console.log('type : ', type);
});
// console.log('subTypeList : ', subTypeList);
.as-console-wrapper { max-height: 100%!important; top: 0; }

The result of processing the data structure includes a list referencing 8 sup- and sub-data structures, each with a type property as requested. This creates a condensed list of these 8 items.

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

Leveraging PHP to retrieve the file path for integration with JavaScript

I am working on a project where I need to retrieve data from an unknown number of .json files and display it on a webpage. To accomplish this, I have written code that loops through a PHP array containing file directory information on the server to dynamic ...

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

Combining the power of Django on the back end with a sleek React front end

The concept Embarking on the creation of a social media platform, I initially developed basic static pages using Django templates. These pages encompassed essential features like user profiles, status feeds, search functionality, and event listings. Howev ...

Angular 1.5 - Component for fetching HTML content with dynamic data

Help needed with using Angular Component method. Developing a main html file with its main controller containing a JSON list of client data: clients: [{ "name": "John Jackson", "age": "21", "hair": "brown", }, { "name": "Janet Doe", ...

Converting a non-JSON string into valid JSON format

Is there a way to transform a string that describes an object into a JSON string using PHP (or Python)? For example, convert this (which is NOT a valid JSON string): var str = "{ hello: 'world', places: ['Africa', 'America', ...

.mouseleave() triggers when exiting a designated boundary area

I'm attempting to implement a roll-up feature for a div when the mouse is over another div. The issue I'm facing is that the roll-up div closes even if the mouse just exits through the bottom border. Is there a way to achieve this using JavaScrip ...

Is it possible to automate a query to an API through PHP and store the results on a local drive?

Recently, I created a webpage that fetches data from an API. However, the response time from the server is quite slow, taking around 10-20 seconds to retrieve the information. To mitigate cross-domain issues, I have set up a PHP proxy for the JavaScript re ...

What could be causing the HTML page to scroll up when the datepicker is initialized in JavaScript?

Wondering about a strange issue with my HTML page built using Laravel Blade. Whenever the date picker is initialized in JavaScript, the HTML page unexpectedly scrolls up. Here's the code snippet located at the bottom of the page: <script type=" ...

Tips for utilizing rowspan and colspan in BootstrapTable

I am creating a table using bootrapTable and would like to know how I can use rowspan or colspan to achieve a table layout similar to the one shown in this image: Click here for image description $table.bootstrapTable({ columns: [{ ...

Vue router is designed to maintain the state of child components without requiring them to

Encountering a strange problem with vue-router. Developed a simple CRUD app for managing users. The app includes four main views: User list and a create button Create view with a form child component that fetches field data from an API within the creat ...

Deploying an Express.js application: The command 'PassengerAppRoot' is invalid, possibly due to a misspelling or being defined by a module not included in the server configuration

I am looking to host an express.js app on cPanel. After successfully installing node, nvm, and npm, I managed to upload all the necessary files to the server and configure the .htaccess file. However, despite my efforts, cPanel's error logs are still ...

Create a React component using the value stored within an object

I am interested in creating an object: import React from "react"; import { Registration } from "../../"; const RouteObj = { Registration: { route: "/registration", comp: <Registration /> } }; export default RouteObj; Next, in a separat ...

WebGL annotations failing to display on the webpage

I'm currently working on displaying a 3D model using Three.js in a web browser and looking to incorporate annotations like the ones shown in this Sketchfab model: Interactive 3D Test. I came across a helpful guide at this link, but I'm facing iss ...

Elevate when the mouse hovers over the button

My current task involves increasing the bottom-padding of a span when the mouse hovers over a button. Here is the button code: <button class="btn btn-success btn-circle" id="myBtn" title="Go to top"> <span id="move" class="fa fa-chevron-up"&g ...

Error connecting to MongoDB database (URI parameter)

i encountered the following error: ** MongooseError: The uri parameter to openUri() must be a string, got "object". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string. ** Please assist me in resolvin ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

What is the best method for designing a function that duplicates and places its own division element?

Modification: Check out the final solution at https://jsfiddle.net/DTcHh/40740/ Latest update: You can find a related post here. In my project, there is a div containing an "add question" (Bootstrap) radio button. When clicked, I want this div to be dupl ...

AngularJS $injector.unpr Error: Understanding and Resolving Common Dependency Injection

As a beginner in AngularJS JavaScript, I have recently started learning and practicing with some small sample programs. However, when attempting this particular code snippet, I encountered an error that I need help resolving. <body ng-app="myApp"> ...

After the ajax call has finished loading the page, I would like to toggle a particular div

When I trigger a click event on an element, it calls a function with Ajax calls. How can I toggle a div (which will be loaded after the Ajax call) once the page is loaded? function triggerFunction(){ $("#trigger_div").trigger("click"); $("#to ...

Retrieve no data from Firebase using Cloud Functions

I am a beginner with Google Firebase and Cloud Functions, and I recently attempted a basic "hello world" program: Established a connection to Cloud Firestore [beta], which contains over 100,000 records. Retrieved the top record from the database. Below ...