Exploring through JavaScript objects

Can someone assist me with traversing each element in this JSON and extracting both the key and value to print as an unordered list?

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"}),
                        "BadamMilk": "Hot Badam Milk",
                        "Bornvita": "Hot Bornvita",
                        "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"
                            })
                        })
                    })

                })
            });

Answer №1

The desired format for the output is not explicitly specified, but here is a method to navigate through your data structure and produce an indented output. Additionally, there is no need for parentheses in the data definition (they have been omitted for readability).

function displayOutput(string, level) {
    var target = document.getElementById("output");
    var newDiv = document.createElement("div");
    var textNode = document.createTextNode(string);
    newDiv.style.marginLeft = (level * 20) + "px";
    newDiv.appendChild(textNode);
    target.appendChild(newDiv);
}

function exploreObject(object, level) {
    for (var property in object) {
        if (typeof object[property] === "object") {
            displayOutput(property, level);
            exploreObject(object[property], level + 1);
        } else {
            displayOutput(property + ": " + object[property], level);
        }
    }
}

exploreObject(dataFeed, 0);

See a live demonstration here: http://jsfiddle.net/example/foo123/

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

The origin of dynamic variables derived from a JSON object

I've been struggling with this one for a week now. Trying to nail it down but no success so far :( Imagine receiving a nested JSON response from an API call like: {"Parameters": { "Name": { "Unparsed": null, "First": "John", ...

How can Python be used to efficiently parse and manipulate large JSON files?

As I dive into a project requiring the parsing and manipulation of massive JSON files in Python, I find myself struggling to efficiently handle these multi-gigabyte-sized documents. The default json library isn't cutting it, as it's proven to be ...

Storing file paths in a database and images in a folder using ASP.NET, JavaScript, and effective methods

Seeking assistance in storing an image file in a folder and path in a database using asp.net and JavaScript. Can you provide guidance on how to retrieve the complete path of the image in JavaScript? I read about security reasons preventing access to the ...

Converting a JSON object into a C# object using deserialization - OpenTSDB

My first experience working with JSON involves extracting data from OpenTSDB. I've developed a c# class for deserializing the JSON, but encountered the error 'Cannot deserialize the current JSON array' as explained below. The c# code used t ...

Struggling to retrieve the Object from a JSON file located at a specific URL

Apologies if this comes across as naive, but my venture into javascript and json is just starting. I'm eager to access the JSON object from the twitter API after executing var myjson; $.getJSON('url of the Object', function(data) { ...

Issue with object not being properly deserialized when making a PUT request through a web API

Currently, I am utilizing web-api 2 along with Postman rest client for testing purposes. Within my method definition, it is structured as follows: [Route("api/bob/user")] [HttpPut] public IHttpActionResult UpdateUser(User user) The structure of the User ...

Execute jQuery function for array iteration

Here is the variable "items" that I have used in the function below: The value of items is [{"daLevel":"DA0","daName":"Da Name 0"},{"daLevel":"DA1","daName":"Da Name 1"},{"daLevel":"DA2","daName":"Da Name 2"},{"daLevel":"DA3","daName":"Da Name 3"},{"daLev ...

Show information from an array

On the index.php page, there is a script that retrieves data from demo.php and presents the outcome in a div. <div class="leftbox"> <?php echo "<div id='proddisplay'>"; echo "</div>"; ?> </div&g ...

Having trouble displaying API values in b-form-select component in Vue.js?

I am using an API to fetch users data and I want to bind these users to a b-form-select component in Bootstrap Vue. However, after making the request, I only see "null" in the b-form-select. Here is my request: getAllUsers() { axios.get(&a ...

The dynamic duo of web development: React and Bootstrap JavaScript

As I work with ReactJS, I have come to understand that using JQuery or vanilla JS to directly manipulate the DOM is not recommended. This is because ReactJS operates using a virtual DOM, which can lead to unpredictable outcomes. My question now is: if I w ...

methods for transferring information from a website to a smartphone using SMS

I am currently in the early stages of learning JavaScript and working on a project that involves creating a form (a web page) to send data to my mobile device via SMS when the submit button is clicked. However, I am unsure how to transfer data from JavaS ...

The synchronization and network bandwidth optimization of Angular and Firebase's three-way binding system

Is it possible to synchronize the text box content across various clients using Angular and Firebase? I am curious to know if Firebase will update the database with each letter I type. How does this process impact network bandwidth? Can you explain how it ...

Is it possible to retrieve all data from a single useMemo in React?

I'm trying to optimize my code by using just one useMemo instead of multiple React.useMemo blocks. Here is the current version: const App = () => { const isChecked = React.useMemo(() => { const source = get(data, 'somesource&apo ...

Designing Buttons and Titles for the Login Page

I'm currently working on developing a straightforward login page in react native and I've encountered some difficulties with styling. Does anyone have tips on how to center the text on the button? Also, is there a way to move the INSTARIDE text ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

Moving data from the bottom of the page to the top

I am facing a situation where I have several foreach loops on a page that calculate the sum of variables. By the end of these loops, a specific variable contains data. However, I now need to display this data at the top of my page before the foreach loop. ...

Jest testing in a Vue child component is failing due to the presence of lodash

In this specific instance of my Vue app, I have globally loaded lodash as a Vue plugin in the main.js file: import _ from "lodash" export default function install(Vue) { Vue.prototype._ = _ Vue.mixin({ computed: { _: () => ...

What is the best way to tile textures in Three.js without causing distortion?

Despite trying various solutions, I am still facing an issue where my textures appear to be stretched or scaled based on the mesh size. In a bid to seek a resolution, here are some key points to note: All textures have dimensions of 64x64 pixels I have p ...

Does React have an event component that detects when a user is actively viewing a specific component, such as a post?

Is there a special React event that fires when the user's gaze is focused on a component? Something like ComponentEnteredShowArea? For instance, videos in Facebook posts play automatically when I direct my attention towards them. It would be ideal i ...

Can you explain the concept of cross referencing classes in Javascript/Typescript?

I am encountering difficulties with cross-referencing classes that are defined in the same file. // classes.ts export class A extends BaseModel implements IA { static readonly modelName = 'A'; b?: B; symbol?: string; constructor(object: ...