JavaScript Decoding JSON with varying identifiers

The JSON data provided contains information about different types of vehicles, such as cars, buses, and taxis.

{  
   _id:"7654567Bfyuhj678",
   result:{  
      CAR:[  
         [  
            "myCar1",
            12233
         ],
         [  
            "myCar2",
            2343
         ],
         [  
            "myCar3",
            5435
         ]
      ],
      BUS:[  
         [  
            "Bus1",
            AAE33
         ]
      ],
      TAXI:[  
         [  
            "myTaxi1",
            463789
         ],
         [  
            "myTaxi2",
            543
         ],
         [  
            "myTaxi3",
            5445
         ]
      ]
   }
}

However, the challenge is that the specific keys like "QWERTY", "PML", "TAXI" are unknown beforehand. The goal is to extract all the data within these keys using a hash table or similar structure, mapping them in pairs like QWERTY myCar1 12233, myCar2 2343 PML Bus1, AAE33, etc.

To achieve this in JavaScript, you can use the following code snippet:

$http.get('http://localhost:3000/transports/'+id)
                        .success(function (transport) {
                            console.log("transport: ", transport);
                        })
                        .error(function (transport) {
                            console.log(transport);
                        });

The JSON data fetched from the URL will be stored in the variable transport.

Your assistance on this matter would be greatly appreciated. Thank you!

Answer №1

Traversing a JSON object is very similar to traversing a plain object. You can use a loop in the same way:

.done(function (data) {
  for ( var key in data.items ) {
    // key == 'item1', then key == 'item2' etc.
    // data.items[key] = [ ["value1", 1234], ["value2", ...], ... ], etc.
    processItem(data.items[key]);
  }
}

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

JavaScript format nested data structure

For my latest project, I am working on a blog using Strapi combined with Nuxt. To fetch the categories and articles data for my blog, I send a JSON object from my front-end application using Axios. { "data": [ { "id": 1, ...

When using Jest, it is not possible to match 'undefined' using 'expect.any(Object)' or 'expect.anything()'

Looking to test the following module. import * as apiUtils from './apiUtils'; export function awardPoints(pointsAwarding) { return apiUtils.callApiService("POST", "points", pointsAwarding); } This is the test in question. it("should call ap ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Breaking down an array into function arguments in TypeScript/JavaScript

I am working with an array of object instances that have different types. var instances: any = []; instances["Object1"] = new TypeA(); instances["ObjectB"] = new TypeB(); Each type has its own methods with unique names and varying numbers of arguments. I ...

Struggling to retrieve JSON data within the code

Recently, I've been receiving a JSON data from Microsoft cognitive services but unfortunately, I'm encountering difficulties incorporating it into my code. Is there something that I might be doing incorrectly? I attempted different approaches su ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

Permanent Solution for HTML Textbox Value Modification

I'm currently working on a GPS project where I am attempting to capture the altitude (above sea level) value in textbox1 and convert it into a ground level value displayed in textbox2. In this scenario, the GPS Altitude (ASL) value is dynamic. For ex ...

A Guide to Parsing JSONArray in Android

How do I handle parsing a JSONArray from a webservice response that is structured like this: <?xml version="1.0" encoding="UTF-8"?> <string xmlns="http://www.somewebsite.com/"><PricingTier ANo='01234567' MsgFlg=''>& ...

What is the order of reflection in dynamic classes - are they added to the beginning or

Just a general question here: If dynamic classes are added to an element (e.g. through a jQuery-ui add-on), and the element already has classes, does the dynamically added class get appended or prepended to the list of classes? The reason for my question ...

When the user clicks on an organizational chart, a new organizational chart will appear in a modal popup

Currently, I am developing a project with Highcharts where I have a specific requirement to display a modal popup when a node on an org chart is clicked. The popup should also contain another org chart. Below is the code snippet I am working with: [link to ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

What is the most effective method for implementing a debounce effect on a field in React or React Native?

Currently, I am working on implementing a debounce effect in my useEffect. The issue is that the function inside it gets called as soon as there is a change in the input value. useEffect(() => { if (inputValue.length > 0) { fn(); ...

Looking for a quick guide on creating a basic RESTful service using Express.js, Node.js, and Mongoose?

As a newcomer to nodejs and mongoDB, I've been searching high and low on the internet for a tutorial that combines express with node and mongoose. What I'm specifically looking for is how to use express's route feature to handle requests and ...

My function doesn't seem to be cooperating with async/await

const initialState={ isLoggedIn: false, userData: null, } function App() { const [state, setState]= useState(initialState) useEffect(()=>{ async function fetchUserData(){ await initializeUserInfo({state, setState}) // encountering an ...

Transforming the image by encoding it to a base64 string using PHP, then including it in a JSON response, decoding it back to an image, and presenting it in

I've been working on a PHP code that fetches an image from a database and encodes it in JSON using base64. Below is the snippet of the code: $query=mysql_query("SELECT Id,Image FROM $table_first"); while ($row=mysql_fetch_assoc($query)) { $ ...

What is the best method for incorporating new data into either the root or a component of Vue 3 when a button is pressed?

One issue I'm facing is the challenge of reactively adding data to either the Vue root or a Vue component. After mounting my Vue app instance using app.mount(), I find it difficult to dynamically add data to the application. As someone new to the fram ...

The CORS Policy error message "The 'Access-Control-Allow-Origin' header is missing on the requested resource" in Next.js

Encountered an issue with CORS Policy error while attempting to redirect to a different domain outside of the project. For example, trying to navigate to https://www.google.com through a button click or before certain pages load. The redirection was handl ...

The self-made <Tab/> element is not functioning properly with the ".Mui-selected" class

I have customized a <Tab/> element and I want to change its selected color using Sandbox demo code export const Tab = styled(MuiTab)({ "&.Mui-selected": { color: "red" } }); However, I've noticed that: 1. Apply ...

"Explore a different approach to file uploading with React Native JavaScript by using either blob or base64 encoding

I am in the process of uploading visuals. When I employ this technique, it functions as expected: formData.append("file",{uri,type,name}); Yet, I prefer not to transmit my visual using the URI. My intention is to divide the visual into distinct sections ...

Generate a variety of data visualizations by utilizing matplotlib in Python with JSON input

Hello everyone, I'm diving into the world of stackoverflow for the first time, so please bear with me if I make any mistakes. I'm currently working on a Flask web application that focuses on conducting surveys. My goal is to generate charts base ...