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

"Could you please help me understand the process of receiving a JSON in an Express

When working with React, I encountered an issue where the JSON data sent to me from the front-end is in a strange format (an object with the data as a string). I am unsure how to convert it back into the object type. This is what I send: const data = { ...

AngularJS encountered an unidentified provider: $routeProviderProvider

I've hit a roadblock with an unfamiliar provider error and can't seem to figure out what I'm missing. Here's the setup: in main.js 'use strict'; angular.module('myApp') .controller('MainCtrl', ['n ...

What is the best way to set up the typeRoots option for proper configuration

I have a unique yarn monorepo structure that is oddly shaped. Here's how it's set up: monorepo root ├── frontend │ ├── dashboard <-- not managed by yarn workspaces │ | ├── src │ | ├── node_modules │ ...

Is it possible to customize the MUI CSS for a specific menu item using the sx prop?

How can I apply the MenuItemStyle to the sx prop of a MenuItem using: const MenuItemStyle = { '&:hover': { backgroundColor: `${theme.color.secondaryHover}`, }, '&:selected, &:selected:hover': { backgroundColor: ...

"Tree panel items in ExtJS 4 are displaying correctly in Firefox, but are mysteriously missing from

While working on my Tree Panel project, I encountered an issue with the display of items in different browsers. The items show up correctly in Firefox but appear empty in Chromium. How is this possible? Here's the JSON data sent to the server: {"tex ...

Tips for refreshing the default style of Material UI select

I'm having trouble customizing the default background color of the first menuItem in the select component. The class I need is not visible when inspecting the element, as the background color disappears upon inspection. Steps to reproduce: 1. Click ...

In search of javascript implementations of the pubhubsubbub protocol that are open source

Can you list out some of the open-source Javascript implementations for the PubSubHubbub protocol, starting with the publishing side? ...

Having trouble capturing screenshots with PuppeteerJS?

I've encountered an issue while working with Puppeteer to capture screenshots from a provided URL. The code I have below doesn't seem to be functioning properly. It keeps showing the error message: [0] Error: Protocol error (Emulation.setDeviceM ...

What is the best way to populate nested elements with jQuery?

I am trying to showcase the latest NEWS headlines on my website by populating them using Jquery. Despite writing the necessary code, I am facing an issue where nothing appears on the webpage. Below is the HTML code snippet: <div class="col-md-4"> ...

A guide on transforming a string into an array of objects using Node.js

Hey everyone, I have a single string that I need to convert into an array of objects in Node.js. let result = ""[{'path': '/home/media/fileyear.jpg', 'vectors': [0.1234, 0.457, 0.234]}, {'path': '/home/med ...

Guide to iterating through an Observable<Object[]> to generate an array of objects

Google Firestore collection named users is structured as follows : { "contactNumber":"0123456789", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e2e7e0e6ece7edc8efe5e9e1e4a6ebe ...

What is the value of x in the equation 2 raised to the power of x equals 800

Similar Question: What is the reverse of Math.pow in JavaScript? 2^x=i If i is given, how can we determine x using Javascript? ...

StorageLimit: A new condition implemented to avoid saving repetitive values in the localStorage

Is there a way to store the text of an li element as a localStorage value only once when clicked? If it already exists in localStorage, a second click should have no effect other than triggering an alert. I'm currently using an if statement inside a ...

Adding a constant to a Vue component

Currently working on developing an application using Vue and TypeScript. I'm focused on refactoring some aspects, particularly moving hard-coded strings from a template to a separate constant. What has been implemented is as follows: export const va ...

Setting the content-type for static assets in NuxtJS

I'm trying to use the Nuxt built-in server to serve the static file /.well-known/apple-app-site-association with a content-type of application/json. Unfortunately, because the file does not have a .json extension, it is returning as application/octet- ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

Building a personalized payment experience using Python Flask and Stripe Checkout

I'm attempting to set up a customized checkout integration with Stripe on my Flask web application and I've encountered some issues. After copying the code from the Stripe documentation (located at https://stripe.com/docs/checkout#integration-cu ...

React application no longer displaying content following the upgrade to React 18 version

My React App was functioning perfectly, but after updating to React 18, MUI v5, and Redux v5, it stopped rendering anything. When I check the terminal, it shows: "webpack compiled successfully" However, in the Chrome console, I see: Warning: In ...

Guide on navigating to a specific step within a wizard using Vue and TypeScript

In this wizard, there are 6 steps. The last step includes a button that redirects the user back to step 4 when clicked. The user must then complete steps 5 and 6 in order to finish the wizard. step6.ts <router-link to="/stepFour" ...

Look into the data with vue.js, but there's not much

1. As a newcomer to vue.js, I encountered some surprising issues while experimenting with examples. The first one arose when I assigned an id to the body tag and included the following JavaScript code: <html> <head> <meta charset="utf-8 ...