How to organize a nested JSON array object in JavaScript

var dataSource = ({
"Items": ({
    "Deserts": ({}),
    "Veg": ({
        "VegPulao": "Veg Pulao",
        "PalakPaneer": "Palak Paneer",
        "PaneerButterMasala": "Paneer Butter Masala"
    }),

    "Chicken": ({
        "Tandoori": "Tandoori special"
    }),
    "Hot drinks": ({
        "Coffe": ({ "Hot": "Hot Coffe", "Medium": "Medium", "Others": ({ "Iris": "Iris Coffe", "Capuccino": "Capuccino" }) }),
        "Tea": ({ "Red": "Red Tea", "Black": "Black Tea" }),
        "Hot BadamMilk": "Hot Badam Milk",
        "Hot Bornvita": "Hot Bornvita",
        "Hot Milk": "Hot Milk"
    }),
    "Juice": ({
        "Mango": "Mango",
        "Berry": "Berry",
        "Grapes": "Grapes",
        "Wine": ({
            "Rose": "Rose",
            "Red wine": "Red",
            "Apple": "Apple",
            "Hard drinks": ({
                "Royal challenge": "Royal challenge",
                "Blender's Pride": "Blender's Pride"
            })
        })
    })
})

});

If you want to organize a complex JSON object similar to the one provided above, we can help!

Answer №1

If you haven't already figured it out,

function customSort(obj, newObj){
    Object.keys(obj).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())).forEach(key=>{
        if(typeof obj[key] === 'object'){
            newObj[key] = {};
            newObj[key] = customSort(obj[key], newObj[key]);
        } else {
            newObj[key] = obj[key];
        }
    });
    return newObj;
}

JSON.stringify(customSort(dataCollection, {}));

This code snippet sorts the keys alphabetically in a case-insensitive manner.

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

Rebalancing Rotation with Three.js

Currently, I am utilizing Three.js and my goal is to swap out an object in the scene with a new one while maintaining the same rotation as the one I removed. To achieve this, I take note of the rotation of the object I'm removing and then utilize the ...

The initial item within the array is either null or empty within the Java programming language

public static void main (String[] args) { Scanner scanner = new Scanner(System.in); int inputs = scanner.nextInt(); String[] array1 = new String[inputs]; String[] array2 = new String[inputs]; for(int i=0;i<inp ...

Symfony2 encountering difficulties in locating file after deployment

Upon launching my project on the live server, I encountered the following error: An error occurred during template compilation ("Could not locate file "@JDareClankBundle/Resources/public/js/".") in "JDareClankBundle::client.html.twig". I have tried clear ...

Can one button be clicked to trigger the activation of another button through a click?

Just as the title suggests, I am wondering how to make this happen? Any guidance would be greatly appreciated! $('.notVisible').click (function(){ alert("I'm the invisible button") }); $('.visible').click (function(){ al ...

Despite Jackson's attempt to call the setter method, the field within the nested object persists

Within a class, there is an embedded static class. During deserialization of JSON, Jackson invokes setters, but some setters do not function as intended. Class definitions: @Entity @JsonIgnoreProperties(ignoreUnknown=true) @JsonPropertyOrder({ "name", " ...

What could be causing my calculations to be inaccurate?

My program is currently reading data from a CSV file and storing it in an array. After storing the data, I want to perform calculations such as finding the average, maximum number, and minimum number. I seem to be stuck and can't figure out where I a ...

Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed. I've noticed that my current implementation doesn't seem to work correctly, a ...

Adjust the field of view of the camera in ThreeJS

I'm currently working on adjusting the field of vision for a camera without having to create a new one. So far, I've successfully achieved this for the position using the following code: camera.position.set() Now, I'd like to implement a s ...

Troubleshooting Google Analytics on Localhost: Investigating Issues with Test Code

I've been working on an HTML file and wanted to integrate Google Analytics into it. After signing up with GA, I received a tracking code to insert into my HTML file within the head section at the very beginning. I followed the instructions and then pr ...

Storing JSON results in cache using Twitter Bootstrap Typeahead

Using the twitter bootstrap library in my application has been a fantastic experience. I am currently working on implementing bootstrap typeahead for autocomplete and facing an issue with caching the results to reduce server requests. During my research, I ...

In Node JS, the variable ID is unable to be accessed outside of the Mongoose

When working with a Mongoose query, I encountered an error where I am trying to assign two different values to the same variable based on the query result. However, I keep getting this error: events.js:187 throw er; // Unhandled 'error' ev ...

I'm trying to figure out how to resolve this issue in IE: SCRIPT1003: A colon is expected

let dataOptions = { @foreach($options as $option) @if($option->option_type == 0) Choose_{{ $option->id}}, @endif @if($option->option_type == 1) ...

Extract information from various files stored in Firestore

I have been struggling to retrieve data from multiple documents despite numerous attempts. The screenshot below displays that I have a collection of 3 documents, and my inquiry is how to extract data from each of them. https://i.stack.imgur.com/bFrIG.png ...

What is the best way to link a button to a form in Angular?

I'm currently utilizing Angular 6.x and I am looking to link a submit button that is located outside of the form in the DOM. Essentially, I want to achieve something similar structurally to this: <button type='submit' form='myform&a ...

What's the best way to extract all the specific key values from a multidimensional array in PHP?

How do I extract the 'name' and 'city' values from the given multidimensional array and store them in separate arrays? $myarray=Array(Array('name' => 'A','id' => '1', 'phone' => ...

Utilize INNER JOIN combined with JSON to retrieve $numrows from the database

Currently, I am working on getting the JSON data to display a specific number of comments for a post in order to automatically update the feed that I have developed. In order to achieve this, I need to combine the 'STREAMDATA table' and the &apos ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

What is the method for defining the maximum stack size in a node.js environment?

I encountered an error when trying to convert a docx file to epub format. Despite increasing the stack size, the task was unsuccessful. The specific error message I received is as follows: RangeError: Maximum call stack size exceeded at Array.filter (n ...

What is the process for javascript selecting a remote-data service?

I recently purchased a new app and am diving into Javascript and AngularJS for the first time. As I try to navigate through the code, I find myself puzzled by how the function in homeService.js is able to utilize remote-data.service.js. Featured below is ...

Does MongoDB have a method to identify the presence of an element within an array?

I am currently working on a query where I need to ensure that a specific string does not appear in an array. The schema I am using looks like this: _id: { type: String, required: true }, ... meta: { user_likes: { ...