You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

You can use it like this:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.
Answer from SLaks on Stack Overflow
🌐
Liquid-technologies
blog.liquid-technologies.com › advanced-data-structures-in-json-part-3-of-4
Advanced Data Structures in JSON: Nested Objects & Arrays
July 4, 2025 - Visualizing these nested structures is key, and tools like the graphical JSON viewer in Liquid Studio JSON Editor can be invaluable for navigating and understanding complex hierarchies. Often, you need to represent a list or collection of items, where each item is itself a complex entity with multiple attributes. This is achieved using an array of objects.
Discussions

How can I access a nested array within a JSON file?
To access a nested array within a JSON file, you can traverse the JSON structure using the array index notation. For example, let’s say your JSON data resembles this structure: {"data": [["apple", "banana"], ["car", "bike"]]}. To retrieve the item “car”, you’d navigate using data[1][0]. ... More on community.latenode.com
🌐 community.latenode.com
0
0
October 29, 2024
Nested JSON Array of Arrays
I am trying to read the following JSON structure to a Dictionary object and conversely create JSON from a Dictionary object containing a list of lists, i.e. the More on community.appian.com
🌐 community.appian.com
0
0
December 2, 2017
JSON object to array of nested JSON
I have a JSON object in cosmos DB(source) which I need to transform into an array of nested JSON objects(similar to source objects)in Cosmos DB(sink). Using the derived column I am facing an error during typecast of complex json to array. Could I get an… More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
create nested json from array of objects dynamically
Copyvar allCards = [ { title: "A", ... + JSON.stringify(result, 0, 4) + ''); ... Sign up to request clarification or add additional context in comments. ... Save this answer. ... Show activity on this post. Here is one way of doing it. Iterate the array of objects, building ... More on stackoverflow.com
🌐 stackoverflow.com
May 10, 2016
Top answer
1 of 5
25

The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var keyword

You don't have any comments in your JSON, but you should remove the var and start like this:

orders: {

The [{}] notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:

"associatedDrug": {
                "name":"asprin",
                "dose":"",
                "strength":"500 mg"
          }

Also, the empty object labs should be filled with something.

Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse() method, or any other parsing method (please don't use eval)

Update 2 answered:

obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name

returns 'aspirin'. It is however better suited for foreaches everywhere

2 of 5
19

I successfully solved my problem. Here is my code:

The complex JSON object:

   {
    "medications":[{
            "aceInhibitors":[{
                "name":"lisinopril",
                "strength":"10 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "antianginal":[{
                "name":"nitroglycerin",
                "strength":"0.4 mg Sublingual Tab",
                "dose":"1 tab",
                "route":"SL",
                "sig":"q15min PRN",
                "pillCount":"#30",
                "refills":"Refill 1"
            }],
            "anticoagulants":[{
                "name":"warfarin sodium",
                "strength":"3 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "betaBlocker":[{
                "name":"metoprolol tartrate",
                "strength":"25 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "diuretic":[{
                "name":"furosemide",
                "strength":"40 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "mineral":[{
                "name":"potassium chloride ER",
                "strength":"10 mEq Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }]
        }
    ],
    "labs":[{
        "name":"Arterial Blood Gas",
        "time":"Today",
        "location":"Main Hospital Lab"      
        },
        {
        "name":"BMP",
        "time":"Today",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"BNP",
        "time":"3 Weeks",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"BUN",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Cardiac Enzymes",
        "time":"Today",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"CBC",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Creatinine",
        "time":"1 Year",
        "location":"Main Hospital Lab"  
        },
        {
        "name":"Electrolyte Panel",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Glucose",
        "time":"1 Year",
        "location":"Main Hospital Lab"  
        },
        {
        "name":"PT/INR",
        "time":"3 Weeks",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"PTT",
        "time":"3 Weeks",
        "location":"Coumadin Clinic"    
        },
        {
        "name":"TSH",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        }
    ],
    "imaging":[{
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        },
        {
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        },
        {
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        }
    ]
}

The jQuery code to grab the data and display it on my webpage:

$(document).ready(function() {
var items = [];

$.getJSON('labOrders.json', function(json) {
  $.each(json.medications, function(index, orders) {
    $.each(this, function() {
        $.each(this, function() {
            items.push('<div class="row">'+this.name+"\t"+this.strength+"\t"+this.dose+"\t"+this.route+"\t"+this.sig+"\t"+this.pillCount+"\t"+this.refills+'</div>'+"\n");
        });
    });
  });

  $('<div>', {
    "class":'loaded',
    html:items.join('')
  }).appendTo("body");

});

});

🌐
Qlik Community
community.qlik.com › t5 › Member-Articles › Parsing-Nested-JSON-Objects › ta-p › 2535112
Parsing: Nested JSON Objects - Qlik Community - 2535112
November 4, 2025 - Unlike the previous post Parsing: Flat JSON - Field Value Pairs this structure has more than just the fields and values it has entity structure. The · name field isn't a standalone name, it's part of the ... sheriff's office isn't just a field ... it's a nested entity, that includes multiple field value pairs.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-access-and-process-nested-objects-arrays-or-json
How to Access and Process Nested Objects, Arrays, or JSON? - GeeksforGeeks
Recursive functions allow you to access and process deeply nested objects or arrays by repeatedly calling the function on nested items. This is helpful when we don't know the exact length of the object. ... const o1 = { o2: { name: "Sourav", contacts: { emails: ["sourav@example.com", "sourav.work@example.com"], phone: "123-456-7890" } } }; function printNested(obj) { if (typeof obj === 'object') { for (let key in obj) { printNested(obj[key]); } } else { console.log(obj); } } printNested(o1); ... For JSON data, you can use JSON.parse() to convert JSON strings into JavaScript objects and JSON.stringify() to convert JavaScript objects into JSON strings.
Published: July 23, 2025
🌐
Codefinity
codefinity.com › courses › v2 › d797f15f-39dd-4abc-8cfd-0d898dd2b885 › 372339e2-bcc5-490c-a5ee-f4d51f680045 › e304b41b-64c3-4141-9977-18b5c16467ff
Learn JSON Arrays and Nested Objects | Understanding JSON Data
This structure is commonly used ... related records together. Nested objects in JSON occur when an object contains another object or an array as one of its values....
🌐
Workiva
support.workiva.com › hc › en-us › articles › 19581207597460-CLP-JSON-Array-of-Nested-Objects
CLP - JSON Array of Nested Objects – Support Center
July 10, 2024 - Enter variety for the Column Name and .name for the JSONPath parameters. Select Pipe for the Delimiter parameter. ... As noted, the dataset has an array (i.e., multiple items) of nested objects. To process each of the varieties individually, row numbers must be added to the dataset.
Find elsewhere
🌐
CodeSignal
codesignal.com › learn › courses › parsing-json-with-csharp › lessons › parsing-json-arrays-and-nested-structures
Parsing JSON Arrays and Nested Structures
Similarly to parsing simple JSON arrays, we can handle nested structures where arrays contain further arrays or objects. This nesting adds complexity but allows for a richer and more detailed representation of data.
🌐
Lokalise
docs.lokalise.com › all collections › keys and files › supported file formats › json nested (.json)
JSON nested (.json) | Lokalise Help Center: Documentation and helpful resources
June 19, 2026 - Unlike flat JSON files, nested JSON files can contain objects within objects, allowing for a deeper hierarchical organization of translation strings.
🌐
Latenode
community.latenode.com › other questions › javascript
How can I access a nested array within a JSON file?
October 29, 2024 - To access a nested array within a JSON file, you can traverse the JSON structure using the array index notation. For example, let’s say your JSON data resembles this structure: {"data": [["apple", "banana"], ["car", "bike"]]}. To retrieve ...
🌐
Appian Community
community.appian.com › discussions › f › general › 11487 › nested-json-array-of-arrays
Nested JSON Array of Arrays
December 2, 2017 - I am trying to read the following JSON structure to a Dictionary object and conversely create JSON from a Dictionary object containing a list of lists, i.e. the
🌐
Micro Focus
microfocus.com › documentation › silk-performer › 205 › en › silkperformer-205-webhelp-en › GUID-2CC23B7F-8C73-414F-A82D-E386B1F3F9F9.html
Receiving Nested JSON Objects and JSON Arrays
The only difference is that they return specified elements from a JSON array instead of properties from a JSON object. dcltrans transaction TMain var jsonParentString : string; jsonParent : number; jsonArray : number; jsonObject : number; begin jsonParentString := "[" "{" "\"Name\": \"Nested ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-access-nested-json-objects-in-javascript
How to access nested json objects in JavaScript?
Accessing nested JSON objects in JavaScript involves navigating through multiple levels of object properties. Nested objects are objects contained within other objects, creating a hierarchical data structure.
🌐
DEV Community
dev.to › iamcymentho › demystifying-nested-data-a-guide-to-accessing-and-processing-objects-arrays-and-json-in-javascript-34im
Demystifying Nested Data: A Guide to Accessing and Processing Objects, Arrays, and JSON in JavaScript - DEV Community
September 15, 2023 - Using nested loops for array traversal. LeveragingforEach,map, and reduce forarraymanipulation. Dealing with multi-dimensional arrays. ... Recursive functions for deep object traversal. Avoiding stack overflow with iterative solutions. Exploring modern solutions using ES6 and beyond. ... JSON(JavaScript Object Notation) is a widely used format for exchanging data between a server and a client, or between different parts of an application.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 153749 › json-object-to-array-of-nested-json
JSON object to array of nested JSON - Microsoft Q&A
Thanks Himanshu for your attention. My issue is now resolved. I used hierarchy to create an array out of my jSON inputs which resolved the issue.
🌐
ArduinoJson
arduinojson.org › version 5 › faq › how to create complex nested objects?
How to create complex nested objects? | ArduinoJson 5
May 21, 2026 - Bag of Tricks · Pitfalls · Release notes · Upgrade guide · To create a nested object, call createNestedObject(). To create a nested array, call createNestedArray(). For example: DynamicJsonBuffer jsonBuffer; JsonObject& root = ...
🌐
Leapcell
leapcell.io › blog › understanding-json-arrays-of-arrays
Understanding JSON Arrays of Arrays | Leapcell
July 25, 2025 - One of its powerful features is ... of arrays, also known as a multi-dimensional array, is a structure where each element of the main array is itself an array....
Top answer
1 of 2
3

The solution below uses the following approach:

  1. Index each item into an object by their respective title value from the allCards collection by using Array.prototype.reduce().
  2. Use Array.prototype.filter() to retain the root items in the collection, while at the same time assign each item as a child to their respective parents if they do exist in the indexed variable.

var allCards = [
  { title: "A", parent_id: "root", has_children: true},
  { title: "A1", parent_id: "A", has_children: true},
  { title: "A11", parent_id: "A1", has_children: false},
  { title: "A12", parent_id: "A1", has_children: false},
  { title: "A13", parent_id: "A1", has_children: false},
  { title: "B", parent_id: "root", has_children: true},
  { title: "B1", parent_id: "A", has_children: true},
  { title: "B11", parent_id: "B1", has_children: false},
  { title: "B12", parent_id: "B1", has_children: false},
  { title: "B13", parent_id: "B1", has_children: false}
];

// index each item by title
var indexed = allCards.reduce(function(result, item) {
  result[item.title] = item;
  return result;
}, {});

// retain the root items only
var result = allCards.filter(function(item) {
  
  // get parent
  var parent = indexed[item.parent_id];
  
  // make sure to remove unnecessary keys
  delete item.parent_id;
  delete item.has_children;
  
  // has parent?
  if(parent) {
    // add item as a child
    parent.children = (parent.children || []).concat(item);
  }
  
  // This part determines if the item is a root item or not
  return !parent;
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 2
1

Here is one way of doing it. Iterate the array of objects, building a new object for each one and store it in a cache so you can directly modify that object when its children are processed. Parents must appear before children for this to work, otherwise you'd have to build in multiple passes.

// define data array
var data = [
    { title: "A", parent_id: "root",has_children: true},

    { title: "A1", parent_id: "A",has_children: true},

    { title: "A11", parent_id: "A1",has_children: false},
    { title: "A12", parent_id: "A1",has_children: false},
    { title: "A13", parent_id: "A1",has_children: false},

    { title: "B", parent_id: "root",has_children: true},

    { title: "B1", parent_id: "A",has_children: true},

    { title: "B11", parent_id: "B1",has_children: false},
    { title: "B12", parent_id: "B1",has_children: false},
    { title: "B13", parent_id: "B1",has_children: false}
];

var root = {};
var parentCache = {};
// for each element definition in the data array
for (var i = 0; i < data.length; i++) {
    var element = data[i];
    var title = element.title;
    // XXX - check for duplicate title here.

    // create a new object and initialize
    var newObj = {"title" : title};
    if (element.has_children) {
        newObj["children"] = [];
    }
    // put this object into its parent
    if (element.parent_id === "root") {
        root[title] = newObj;
    } else {
        // XXX - if the parent isn't defined first this will fail
        var parent = parentCache[element.parent_id];
        parent.children.push(newObj);
    }
    // store this object in case it is a parent
    parentCache[title] = newObj;
}

console.log(JSON.stringify(root));
Top answer
1 of 1
4

Your method already looks good! I would only make a couple small changes to the logic as follows:

  1. The if (this._children.length > 0) isn't necessary as the for loop will make the check for you
  2. Instead of using a standard for loop, I would prefer a for..of loop. Typescript will transpile this so it will work in any environment
  3. I prefer early returns to nested statements. Because of this, I would recommend storing the result variable in as small a block as possible

With these changes:

public findNode = (id: any): TreeNode => {
  if (this._id === id) {
    return this;
  }

  for (const child of this._children) {
    const result = child.findNode(id);
    if (result) {
      return result;
    }
  }

  return null;
}

Also, here's a couple Typescript specific notes:

  1. Avoid any like the plague. When you use any you are telling typescript to effectively ignore any mistakes in your code. Given your data structure, it looks like id should be of type string
  2. I highly recommend turning on strictNullChecks. This will help prevent a large class of errors
  3. Methods are public by default in Typescript, with this in mind I recommend dropping the public modifier in most cases as it is redundant. However, this does not apply if you are working on a team with developers who generally work with other languages as it could lead to confusion in the team. For example, in C# the default is that all methods are private

With these changes:

findNode = (id: string): TreeNode | null => {
  if (this._id === id) {
    return this;
  }

  for (const child of this._children) {
    const result = child.findNode(id);
    if (result) {
      return result;
    }
  }

  return null;
}