Using ES6 filter to retrieve an array of keys from an object based on the parent key

Currently, I am working on a method to retrieve an array of object keys representing currencies associated with a specific country. However, my current implementation only returns all currency values in an array.

I aim to utilize ES6 methods exclusively without resorting to other iterators.

Example: Desired Output

If the filter is set based on the country code 'US', the expected result should be an array containing ['USD'].

const myArr = Object.keys(myJSON.countries).filter((k) => (Object.keys(myJSON.countries[k].currencies)[0]) where country === 'US');

Output: ['USD']

This request is linked to a previous inquiry -> ES6 Map to return an array of object keys only

Assistance in achieving this goal would be greatly appreciated. Here's the provided code:

const elem = document.getElementById('currencyList');
var myJSON = {
  "countryCode": {
  "Australia": "AU",
  "United States": "US",
  "Britain": "GB",
  "Japan": "JP",
  "India": "IND",
  "France": "FR",
  "Russia": "RS"
},
"countries": {
  "AE": {
    "currencies": {
    "AED": {
      "isDefault": true
    }
    }
  },
  "AL": {
    "currencies": {
    "ALL": {
      "isDefault": true
    }
    }
  },
   // Rest of JSON data ...
};

function getData() {
const myArr = Object.keys(myJSON.countries).map((k) => (Object.keys(myJSON.countries[k].currencies)[0]));
console.log(myArr);  

  for(var i=0; i< myArr.length; i++) {
  el = document.createElement('option');
  el.textContent = myArr[i];
  el.value = myArr[i];
  elem.appendChild(el);
  }


}
<button onclick="getData()">Get Data</button>
<br />
<select id="currencyList">

</select>

Answer №1

To retrieve information from a country's JSON tree, simply input the country code using array syntax. It is advised to verify the existence of the code beforehand.

// If preferred, extract the country code from an HTML element
const countryCode = "CA";
const countriesArray = Object.keys(myJSON.countries[countryCode].languages);
console.log(countriesArray); // ["English", "French"]

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

Is there a way to direct the user's cursor to a specific location on the page when they hover over an image?

I'm interested in creating a script that can manipulate the user's mouse position when they hover over an image. For example, if I hover over the image, I want the mouse to be dragged lower towards a specific text. Is there a method to achieve th ...

Substitute dynamic Angular expressions with fixed values within a string

Inside my angular controller, I am defining a stringTemplate containing expressions like "{{data.a}} - {{data.b}}". Along with that, I have an object named data with values {a: "example1", b: "example2"}. My goal is to find a way to replace the dynamic ex ...

What is the best approach to using two controllers simultaneously?

In my webpage, there is a left sidebar with its own controller running in the background. On the right side, I have a view of states that are dependent on the left side (a classic ui-view scenario). I am looking to update variables in the sidebar's co ...

An observer is handed to me when I receive an array as a parameter

How can I use an array as a parameter instead of just receiving an observer? When trying to utilize the array, all I get is an observer. The data appears correctly when using console.log in the function that fetches information from the DB. Despite attem ...

Checking the existence of a page on a custom server with Next.js

Utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4729223f33077e69766970">[email protected]</a> on a custom server with express. How can I determine in my server.js whether the next.js page exists before ma ...

Step-by-step guide to performing a linear search within the Python String Class

I am struggling to find specific characters in a string list. Take for instance, string_list = ['sasasd']; I want to locate 'sa'. Even though the linear function should return True, I have attempted numerous times without success. clas ...

Custom Script for Single Tumblr Entry

While I know it's possible to edit the HTML/AngularJS for the overall posts on a Tumblr blog homepage, I'm wondering if there is a way to insert a custom <script>...</script> into individual posts. I have some specific JavaScript task ...

JavaScript code - Empty values in an array

I'm facing a unique challenge: I need to make an ajax request to another URL (URL2) while on a specific page (URL1), retrieve the data and create an array from it for later use. To achieve this, I have to run code in the console while on "URL1". Here ...

Only collapsing the uppermost level in the CSS hierarchy

Within my template, I have utilized the same tree structure code that was referenced in a previous question found at this link. The solution provided in that question initializes the page with the entire tree collapsed (view jsfiddle). My goal is to modif ...

executing concurrent npm tasks on a Windows operating system

After setting up an npm parallel script in my package.json, I noticed that it works smoothly on a mac but encounters issues when run on windows: "myScript": "nodemon ./server.js & cross-env NODE_ENV=development webpack-dev-server" However, when the s ...

Move the sprite to the center bottom of the orthographic camera

Looking for help positioning sprites at the bottom center of the orthographic camera. Here is the current setup - The object: function Obj() { const texture = useLoader(THREE.TextureLoader, loadedimg); const spriteRef = useRef(); return ( < ...

The form is not registering keypress events

Currently facing an issue with this piece of code: <form> <div class="searchBarDiv"> <input class="searchBar" id="search" type="search" placeholder="Search" onkeypress="search();"> </div> </form> The search(); fun ...

Instructions for implementing a jump event with Javascript on Wordpress

I recently created a page on my Wordpress site with a large amount of content divided into different rows. I'm looking to add jump-to-section links at the beginning of each row and a jump-back-to-top link for easy navigation. However, I'm unsure ...

Using Datatables with Jquery and Bootstrap 5 to generate a dynamic dropdown menu within a row and send the selected data to

Utilizing Datatables has been a great experience for me as I attempt to retrieve user details from the database using Php/Sql and generate a bootstrap 5 dropdown to display the employees as options. Fortunately, the dropdown is successfully showcasing the ...

Testing a React component to ensure that it correctly handles clicks occurring outside

Utilizing the solution found in this particular answer to address clicking outside of a component: componentDidMount() { document.addEventListener('mousedown', this.handleClickOutside); } componentWillUnmount() { document.removeEventLis ...

The android application experiences crashing issues when utilizing the position or zIndex style properties within a react-native environment

In my code, I am attempting to display a semi-transparent black screen over my page in order to show a message or prompt in the center. I have tried using zIndex or elevation with position:'fixed' or position:'obsolet', and it works per ...

Develop a dynamic SwiftUI component for a calendar-like view that can scroll horizontally

I am tasked with creating a scrollable horizontal calendar-style view, similar to the example shown here. My ultimate goal is to build an infinitely scrollable view, but I am encountering some challenges that I am unsure how to tackle. Below is the code I ...

What's the rationale behind receiving the second before the first?

I've been digging into ES6 promises, and I thought I had a handle on it for a moment. However, it seems like I may have hit a roadblock. What I'm aiming to do is handle a series of file operations where each operation depends on the completion o ...

The server is unable to process the request for /path

After browsing various posts, I am still unable to identify the root cause of my issue. I am developing a donation page for an organization and need to verify if PayPal integration is functioning correctly. The error I am encountering lies between my form ...

Is there a way to save this array into the database?

How do I convert the array values into a string to insert them into the database? $myArray = Array ( [0] => Array ( [code] => 1 [name] => Array ( [content] => Ohtels Villa ...