How can you utilize JavaScript to access arrays contained within objects?

Imagine we have a JSON stored in a variable named response:

{
    "brands": {
        "Honda": [
          "Accord",
          "Civic"
        ],

        "Porsche": [
          "Cayenne",
          "Cayman"
        ]
    }
}

We want to retrieve the models within each brand. For instance:

for ( var car_brands in response.brands ) {
    console.log(car_brands); // would print Honda, Porsche etc.
}

How can we iterate through car_brands and also obtain the models (arrays) inside each one like Accord, Civic, etc. at the same time?

Perhaps a well-structured JSON format could simplify this parsing process.

Answer №1

To access the value, utilize the property indexer syntax like this:

var car_brandsArray = response.brands[car_brands]

Next, iterate through them using a for loop:

for ( var car_brands in response.brands ) {
    console.log(car_brands); // will log Honda, Porsche etc.
    var car_brandsArray = response.brands[car_brands];
    for (var i = 0; i < car_brandsArray .length; i++) {
        console.log(car_brandsArray[i]); // will log Accord, Civi
    }
}

Alternatively, you can directly log the array:

for ( var car_brands in response.brands ) {
        console.log(car_brands); // will log Honda, Porsche etc.
        var car_brandsArray = response.brands[car_brands];
        console.log(car_brandsArray);
    }

Answer №2

When looping through:

for(var vehicle_brands in response.brands) {
}

You are actually iterating through the indexes (in objects) rather than the values (for in loops through properties).

To retrieve the array:

for(var vehicle_brand in response.brands) {
    var car_vehicle = response.brands[vehicle_brand];
}

To iterate through its values:

for(var vehicle_brand in response.brands) {
    var car_vehicle = response.brands[vehicle_brand];
    for(var index = 0; index < car_vehicle.length; i++) {
        //perform any actions on car_vehicle[index] here;
    }
}

Answer №3

for ( var car_brands in response.brands ) {
    for(var model in response.brands[car_brands]) {
        console.log(model);
    }
}

You were so close, just needed an additional loop :)

Alternatively, you can achieve it using Array.forEach:

response.brands.forEach(function (brand) {
    brand.forEach(function (model) {
        console.log(model);
    });
});

My personal preference is the Array.forEach method.

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

What is the best way to format the content with Tailwind CSS?

I have been trying to customize the appearance of my header item container, which includes a home icon. The issue I'm facing is that despite styling the icon and other elements within the container using Tailwind CSS classes, the changes are not refle ...

Develop a client-side API utilizing various libraries

After completing the server side of an API that delivers HTML via JSON using REST through CodeIgniter, I am now exploring how to create a client-side API with JavaScript. The goal is to retrieve data from the server through the API, display it in the DOM, ...

Keeping the page url intact after refreshing in React - How can I achieve this?

Within my React application, I have implemented a functionality where the respective page names are stored in the local storage based on the clicked page. For instance, if the route is http://localhost:3000/Products, then the name Products is stored in the ...

Text hyperlink populates form fields

I am interested in learning how to create a clickable text link that can automatically populate specific information in a form located above it. For example, I have a donation form with fields for amount, country, and projects. Below this form, there are ...

Is there a way to perform unit testing on JavaScript code that runs following the completion of a CSS transitionEnd event

I am working with a bootstrap modal window and using qunit+sinonjs (fake timers). However, I have noticed that one element (div class='modal-backdor') remains on the page despite my efforts. You can view the issue here: http://jsfiddle.net/valu ...

Tips for creating a popout feature for a YouTube player and getting the video to play

Currently, I am facing an issue with my YouTube player. Whenever I try to play a video using the YouTube API, it redirects to another page before starting playback. Is there a way to make the player pop out on the same page when a user clicks on an image, ...

Is there a way to produce a unique color using Stylus CSS?

Currently, I'm utilizing Express for Node.js and Stylus as the CSS engine. While Stylus is great, I'm facing some challenges in passing color variables or generating random colors. Despite attempting to use the javascript API for stylus, I find m ...

How can you handle a JSON field that is missing during deserialization and set it as

I came across a JSON structure that I need to deserialize, which is as follows: { "a": "foo", "b": { "c": "bar" } } However, sometimes the b field is not present, like this: { "a": "foo" } Below is the class I am using for deser ...

Why can't I seem to print the total sum of numbers stored in the React-Redux state?

Seeking assistance to understand why the "sum" value, which represents the sum of two numbers entered in the input boxes labeled "numOne" and "numTwo", is not being displayed on the user interface. Please refer to AddNum.jsx for more information. Below is ...

Why am I struggling to properly install React?

C\Windows\System32\cmd.e X + Microsoft Windows [Version 10.0.22621.2715] (c) Microsoft Corporation. All rights reserved. C:\Users\user\Desktop\React>npx create-react-app employee_app npm ERR! code ENOENT npm ERR! s ...

Querying data in Laravel from a table with two foreign keys referencing the same table

I am facing an issue with mapping relations in Laravel Eloquent for two tables: teams and games. The teams table has id, group_id, and name fields, while the games table includes id, home_team_id, away_team_id, date, and score. The problem arises from the ...

What is the best way to compare and identify the variances between two JSON documents in Marklogic using JavaScript?

Is there a way to analyze and compare two JSON documents in Marklogic using JavaScript to identify any differences between them? ...

Tips for correctly linking an Event Listener to the worldwide 'window' in Angular 6 and higher

Situation Within our Angular 6 application, an iframe is embedded to showcase third-party data. To facilitate secure cross-domain communication, the child iframe sends messages to the parent Angular app using window.postMessage() API. To receive these mes ...

Node JS express throwing errors when attempting to redirect

Currently, I am delving into learning the fundamentals of Node.js + MongoDB as well as some interconnected tools. However, I have hit a roadblock with a straightforward login screen that I created. The objective is simple: upon entering correct credentials ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

Steps for accessing the latest entry in the database

Within my database, there exists the following record: timer_id = 1 time = 498 Despite my efforts to retrieve the record in the 'time' column using the code below, I am unable to fetch the current record: <script> function start(){ ...

The three.js raycaster is able to detect objects both in front of and behind the specific object I am trying to select

I am currently working on rendering a 3D model of a house using Three.js and encountering an issue with the raycaster in my code. The problem I'm facing is that it's selecting every object both behind and in front of the specific object I want to ...

Having trouble with Npx and npm commands not running in the VSCode terminal?

I am currently facing an issue while attempting to set up a react app in vscode using the command npx create-react-app my-app. It seems like the command is not working properly. Can anyone provide guidance on what steps I should take next? Despite watchin ...

Unable to retrieve the current status of Li from the backend code

I have created a code snippet to load controls on different tabs by using li elements with the attribute runat=server. However, I am facing an issue where I need to load controls based on the active li tab. How can I determine which tab was clicked from t ...

Python encountering errors while attempting to load JSON file

I have a text file containing the following json: { "data sources" : [ "http://www.gcmap.com/" ] , "metros" : [ { "code" : "SCL" , "name" : "Santiago" , "country" : "CL" , "continent" : "South America" , "timezone" : -4 , "coordinates" : {"S" : 33, "W" : ...