Converting JSON arrays with nested "nth level" objects into a multidimensional array

Looking for guidance on converting a nested object into a multidimensional array.

[{
  "name": "level1",
  "subCategory": [{
    "name": "level2",
    "subCategory": [{
      "name": "level3",
      "val": 1,
      "subCategory": null
    }]
  }]
}, {
  "name": "level1",
  "subCategory": [{
    "name": "level2",
    "subCategory": [{
      "name": "level3",
      "val": 2,
      "subCategory": null
    }]
  }]
}, {
  "text": "level1",
  "subCategory": [{
    "name": "level2",
    "subCategory": [{
      "name": "level3",
      "val": 3,
      "subCategory": null
    }]
  }]
}]

Transforming it to:

[
  ["level1", "level2", "level3", 1]["level1", "level2", "level3", 2],
  ["level1", "level2", "level3", 3]
]

Answer №1

By utilizing the power of Array.prototype.forEach()

The forEach() function is executed once for each element in an array.

var data = [{ "name": "level1", "subCategory": [{ "name": "level2", "subCategory": [{ "name": "level3", "val": 1, "subCategory": null }] }] }, { "name": "level1", "subCategory": [{ "name": "level2", "subCategory": [{ "name": "level3", "val": 2, "subCategory": null }] }] }, { "text": "level1", "subCategory": [{ "name": "level2", "subCategory": [{ "name": "level3", "val": 3, "subCategory": null }] }] }],
    result = [];

function iterateArray(array, names) {
    names = names || [];
    array.forEach(function (element) {
        var n = names.concat(element.name);
        if (Array.isArray(element.subCategory)) {
            iterateArray(element.subCategory, n);
        } else {
            result.push(n.concat(element.val));
        }
    });
}

iterateArray(data);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Answer №2

Take a look at this JSFiddle link

var data = [{
  "name": "level1",
  "subCategory": [{
    "name": "level2",
    "subCategory": [{
      "name": "level3",
      "val": 1,
      "subCategory": null
    }]
  }]
}, {
  "name": "level1",
  "subCategory": [{
    "name": "level2",
    "subCategory": [{
      "name": "level3",
      "val": 2,
      "subCategory": null
    }]
  }]
}, {
  "text": "level1",
  "subCategory": [{
    "name": "level2",
    "subCategory": [{
      "name": "level3",
      "val": 3,
      "subCategory": null
    }]
  }]
}];

function convertData(data) {
  var result = [];
  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    var level1 = item.text;
    var level2 = item.subCategory[0];
    var level3 = item.subCategory[0].subCategory[0];
    result.push([item.text, level2.name, level3.name, level3.val]);
  }
  return result;
}

console.log(convertData(data));

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

Status and route redirection in Vue instance management

I am looking to establish a global status property for my application using vue.js and vue-router. This property should be shared between components and used to control access to certain routes based on its value. For instance, I want to redirect all rout ...

Tips for using tooltip.format() to access an array of objects in anychart.js

Having difficulty displaying an array of objects in the tooltip of an Anychart.js map. I know we can access the dataset using %[name of property in data set]. The structure of my dataset is as follows: { "country": "Austria", &q ...

Is it possible for promises and $(data).each in jQuery not to work together?

My AJAX handler contains an each() loop to push data into my temp array. However, I am encountering an issue where the array remains empty after the loop. This is puzzling, as I have used promises with each() before without any problems. var temp = []; $. ...

The website becomes unresponsive and locks up after being on the same page for several

We are dealing with a PHP web application that heavily utilizes javascript and jquery. The main issue we are facing involves a create/read/update/delete page where users can modify content. These modifications occur using AJAX, which prevents a full page r ...

Choose arrays that have the specified value in Jmespath

Looking at the following JSON data: { "users": { "alpha": [ "read", "annotate", "write", "delete", "manage" ], "beta": [ " ...

The request response was a JSON object that started with the keyword "POST"

My frustration is growing as I encounter a strange issue with the stack template I purchased from envato market. Every time I attempt a simple ajax request, the json returned from my PHP script seems to be invalid. Interestingly, the exact same code works ...

AngularJS utilizes $location but includes a refresh option

Back when I used ui-router, I recall there was a command like $state.go('/',{reload:true}). However, with normal ngRoute, how can I navigate to a page and also refresh it? I haven't found any option in $location. ...

The resolver function is ineffective when dealing with promise objects in Node.js

When attempting to utilize the Promise function in Node.js for file reading, unexpectedly the return promise resulted in {}. The sample code is provided below: http.createServer(function(req, res) { var readPath = __dirname + '/users.json'; ...

Bookshelf.js has implemented a new feature where it automatically encrypts passwords with bcrypt every time data is updated

My User Model is var Bookshelf = require('../../db').bookshelf; var bcrypt = require('bcrypt'); var Promise = require('bluebird'); var Base = require('./../helpers/base'); // Custom user model var Custom_User_Mod ...

Is there a way to create an interval that activates when hovering over a button with a cursor in JS / HTML, and automatically clears when the cursor moves away from the button?

Take a look at this snippet of my code: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function mouseOn() { function int() { document.getElementById("hover").click(); ...

What is the process of extracting the query and hash parameters from a URL using JavaScript?

Here is a URL: http://local.evibe-dash.in/tickets/123?ref=avl-error#10610 I'd like to extract ref=avl-error and 10610 into two separate variables. For instance, something like this: var1 = 'avl-error'; var2 = 10610; How can I achieve thi ...

What is the best way to append an element to an array using the index value "array[total number of items in array + 1]"?

I'm currently working on a software project that involves enabling users to input an element to an array: #include <stdio.h> #include <cs50.h> int main(void) { string words[] = {"apple", "bear", "cards"}; ...

Issues with finding your way

Whenever I am in the History.js file and click on a product list item to navigate to another page for more details and contact the seller, the issue arises. When I click on an item in History.js, nothing happens on that page. However, when I switch to Home ...

What are the common reasons for ajax requests to fail?

Every time I try to run the code with the provided URL, the alert() function in the error: function is triggered. Can someone please assist me with this issue? $("#button").click(function(){ $("#form1").validationEngine(); if($('div input[typ ...

Issue with Ajax sending undefined variable to PHP index

Is it possible to display the variable num in a php page? An error message is appearing: Notice: Undefined index: num in C:\xampp\htdocs\javas.php on line 4 Here is the PHP code snippet: <?php $lol = $_POST['num']; echo " ...

Creating a container with polymorphic behavior in C++: A comprehensive guide

Regarding a specific issue: Our grids are quite large. Each point on the grid contains two fields with different types of result arrays. The first array is 3D, consisting of three coordinates (i,j,k) and five physical data points in each point (pressure, ...

Guide to converting an arraylist of custom objects into JSON using JavaScript

I have a List returned to the jag. It is of type (java.util.List) and I need to print it as a json. var storeForum = Packages.org.wso2.carbon.forum.registry.RegistryForumManager; var forum = new storeForum(); var start = request.getParameter(&a ...

Display information on a web page based on user input using HTML

I've hidden other p tags and divs using display:none, How can I make them visible after inputting my name? I'd like to type in my name and reveal all the content within the previously hidden div <form method="post"> <p> < ...

Strategies for effectively managing numerous API requests

My current setup involves fetching about five API calls simultaneously. While it works at times, most of the time it results in a fetch error. Is there a way to prevent these errors from occurring when running the API calls? app.post("/movie/:movieN ...

An individual array incorporated into a two-dimensional array

Check out this code snippet: #include <stdio.h> #include <math.h> int main() { int d, a[3][3] = {{2, 4, 5}, {6, 7, 8}, {9, 10, 11}}; for (d = 0; d < 5; d++) { printf("a[%d] = %d\n\n", d, a[d]); } ...