What is the best way to choose the member variables in this specific data structure?

I have been assigned the task of retrieving the cities from various countries, but I am unsure of the best approach to do so. How can I easily extract city names like:

For example, for USA it would be NYC and SFO.

I attempted using the code snippet cityData[0].children[0], however, it simply returns Object object.

What is the most efficient way to access the cities for each country?

var cityData = [
    {country: "USA", children:[
        {"NYC": ["60%", "70%", "80%"]}, 
        {"SFO": ["40%", "30%", "20%"]}
    ]},
    {country: "Mexico", children:[
        {"Mexico City": ["80%", "80%", "80%"]}, 
        {"Cancun": ["20%", "20%", "20%"]}
    ]},
    {country: "Canada", children:[
        {"Toronto": ["50%", "60%", "60%"]}, 
        {"Vancouver": ["50%", "40%", "40%"]}
    ]
}];

Is there an alternative method to retrieve the city name other than trying to access it with cityData[0].children['NYC'] and cityData[0].children['SFO']?

I'm looking to target both cities with a single selector (if possible).

Feel free to suggest any changes to the data structure that might make this process easier.

Answer №1

To retrieve the keys of the objects you are examining, you can utilize the Object.keys method which will provide an array containing all the keys. By applying a map function, you can extract the keys from each object and generate an array of cities.

cityData[0].children.map(itm => Object.keys(itm)[0])

var cityData = [
    {country: "USA", children:[
        {"NYC": ["60%", "70%", "80%"]}, 
        {"SFO": ["40%", "30%", "20%"]}
    ]},
    {country: "Mexico", children:[
        {"Mexico City": ["80%", "80%", "80%"]}, 
        {"Cancun": ["20%", "20%", "20%"]}
    ]},
    {country: "Canada", children:[
        {"Toronto": ["50%", "60%", "60%"]}, 
        {"Vancouver": ["50%", "40%", "40%"]}
    ]
}];


console.log(cityData[0].children.map(itm => Object.keys(itm)[0]))

Answer №2

give this a shot

   for(const property in cityData[0].children[0]) {
       console.log(property);
    }

Answer №3

If you want the specific syntax mentioned, you can achieve it by preprocessing the arrays of children to convert them into objects...

var cityData = [
    {country: "USA", children:[
        {"NYC": ["60%", "70%", "80%"]}, 
        {"SFO": ["40%", "30%", "20%"]}
    ]},
    {country: "Mexico", children:[
        {"Mexico City": ["80%", "80%", "80%"]}, 
        {"Cancun": ["20%", "20%", "20%"]}
    ]},
    {country: "Canada", children:[
        {"Toronto": ["50%", "60%", "60%"]}, 
        {"Vancouver": ["50%", "40%", "40%"]}
    ]
}];

cityData.forEach(country => {
    let childrenObj = {}
    country.children.forEach(city => {
        let key = Object.keys(city)[0]
        childrenObj[key] = key
    })
    country.children = childrenObj
})

console.log(cityData[0].children['NYC'])

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

Emphasize the most recent file during the document upload process and ensure the scroll bar moves accordingly to the document

I am currently working on a feature where the scroll bar should move to the newly uploaded document in a list of documents. When I upload a new document, I want the scroll bar to automatically move to that document. Currently, the highlighting changes to t ...

What is the best way to conceal the standard 'X' close button within a magnific popup interface?

I implemented the Magnific-popup plugin in my jsp to show messages to users. Here is the code I used to open Magnific Popup: $.magnificPopup.open({ items: { type: 'inline', src: '#idOfSomeDivInPage' }, focus: '#some ...

Issue with Mongoose Promise failing to transfer data to the following chain

When querying MongoDB using mongoose with promises, I encounter an issue where the result is only accessible in the initial .then(function(results){ // can send the result from here..}). However, when I manipulate the results and attempt to pass them to th ...

React's setState method may not trigger a re-render

I am currently working on a personal project using React for the front-end and Node for the back-end. One part of the application involves counting the entries when a user submits an image URL, updating it on the server, and then re-rendering it on the fro ...

Error in TypeScript: It is not possible to use a component with MUI styling as a JSX element

I can't figure out what's going wrong. I'm attempting to include a child component in the main page, and I have a feeling it has something to do with MUI styles being applied at the end. I removed all unnecessary code and still encounter thi ...

Tips for capturing the interaction between a jQuery Dialog and its Parent

Within the parent HTML, there is a call that triggers a JavaScript function. <div class="data"> <form:input title="Building" styleClass="content contractorDisable" maxlength="5" size="6" path="fireImpairForm.bldCode" />&nbsp; <a hre ...

Error: Jest react testing encountered an issue when attempting to read the property 'type' from an undefined value

While conducting tests on my app components created with the material UI library using jest and enzyme, I encountered an error in one of my packages. Here is a screenshot of the error: Click here to view ...

Can one determine if a webpage is being displayed within an Infragistics igDialog?

Occasionally, my web page is displayed without a container and other times it's embedded within an igDialog of another container page, based on the user's navigation throughout our web application. Is there a way, using pure javascript or jQuery ...

Execute an AJAX call to remove a comment

Having some trouble deleting a MySQL record using JavaScript. Here is the JavaScript function I am trying to use: function deletePost(id){ if(confirm('Are you sure?')){ $('#comment_'+id).hide(); http.open("get","/i ...

Save an automatically generated number into a variable and use it to reference an image file for display. This process can be accomplished using JavaScript

I'm having trouble getting my images to display randomly on a page. The images are named 0 - 9.png and I am using a pre-made function for random number generation. However, when I try to call on this function later down the page, nothing appears. It ...

Visual Studio 2017, ASP.NET framework, Typescript programming language, and node package manager

My ASP.net application in Visual Studio used to only utilize JavaScript, but now I am looking to incorporate Typescript. While the installation and transpiling process went smoothly, I encountered an issue when attempting to import modules. I decided to u ...

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

Exploring ways to personalize Angular UI Bootstrap tabs to match the styling of Angular Material tabs

Currently, I am utilizing Angular UI Bootstrap in my project. <html ng-app="ui.bootstrap.demo"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script> <script src="//ajax.googleapis.co ...

Incorporate content from a single HTML file into a different one

Hello, I am working with two HTML documents - let's call them index.html and index2.html for this example. I am looking to embed all the code within the body tag of index2.html into a section within index.html. Is there a way to create this connectio ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...

The Discord.js command outright declines to function

I'm having trouble with a code that I'm working on. The goal is to create a command that is enabled by default, but once a user uses it, it should be disabled for that user. However, when I try to execute the code, it doesn't work at all and ...

The error "TypeError: ollama.chat is not a function" has occurred when trying to use the ollama module in

Currently, I am grappling with a Node.js project that requires me to utilize the ollama module (ollama-js). The problem arises when I invoke the async function chatWithLlama() which contains ollama.chat(), resulting in the following error being thrown: Ty ...

Tips for converting a date string to a date object and then back to a string in the same format

I seem to be encountering an issue with dates (shocker!), and I could really use some assistance. Allow me to outline the steps I have been taking. Side note: The "datepipe" mentioned here is actually the DatePipe library from Angular. var date = new Dat ...

A JavaScript async function with a nested call inside

Below is my node function for the API server: router.post('/find', async (req, res) => { try { const firewalls = []; let count = 0; const devices = await Device.find({ ...req.body }); devices.forEach(async (item) => { ...

Implementing a variable for an array in Angular 4: A step-by-step guide

I need help determining the correct value for skill.team[variable here].name in Angular, where all team names are retrieved from the skill. Below is the code snippet: HTML <select [(ngModel)]="skill.teams[1].name" name="teamName" id="teamName" class= ...