Changing the names of object keys in JavaScript by utilizing a conversion object

Let's dive right in:

I have a list of countries along with their respective values:

{
Mainland China: 14375,
Japan: 20,
Thailand: 19,
Singapore: 18,
South Korea: 15,
Hong Kong: 14,
Taiwan: 10,
Germany: 8,
Malaysia: 8,
Macau: 7,
France: 6,
Vietnam: 6,
Australia: 12,
United Arab Emirates: 4,
Canada: 4,
Italy: 2,
Philippines: 2,
Russia: 2,
UK: 2,
US: 8,
Cambodia: 1,
Finland: 1,
India: 1,
Nepal: 1,
Spain: 1,
Sri Lanka: 1,
Sweden: 1,
}

I want to change the keys of the object to represent each country's 2-letter code:

{
cn: "14375"
jp: "20"
th: "19"
sg: "18"
kr: "15"
sk: "14"
tw: "10"
de: "8"
my: "8"
mo: "7"
fn: "6"
vn: "6"
au: "12"
ae: "4"
ca: "4"
it: "2"
ph: "2"
ru: "2"
gb: "2"
us: "8"
ci: "1"
fi: "1"
in: "1000"
cp: "1"
es: "1"
lk: "1"
se: "1"
}

Is there a straightforward way to accomplish this? I believe using another object like the one below will be essential:

var CountryList = {
'Afghanistan': 'AF',
 'Albania': 'AL',
 'Algeria': 'DZ',
 'American Samoa': 'AS',
 ...
 'Zambia': 'ZM',
 'Zimbabwe': 'ZW',
 'Åland Islands': 'AX'
}

I have managed to make it work on a small scale, but I'm struggling to find a way to do it for each item.

Here is the screenshot from Google Chrome output: https://i.sstatic.net/SmBJe.png

Here are the steps I need to follow: 1) Retrieve data from Google Scripts 2) Convert integers to strings 3) Convert country names (keys) to their 2-digit codes.

As you can see, I have successfully completed steps 1 and 2.

Full JS File:

var countriesObj = {};
var infected_dataINT = {};
var infected_data = {};
  const url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";

  // Declare an async function
  const getData = async () => {
  // Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled 
  // When the variable is fetched, use the .then() callback to carry on 
    const DataJSON = await fetch(url).then(response => 
      response.json()
    )

    return await DataJSON
  };



  console.log(getData());

  getData().then(result => {
    //console.log(result);
    infected_dataINT = result;
    console.log(infected_dataINT);

    function toString(o) {
      Object.keys(o).forEach(k => {
        if (typeof o[k] === 'object') {
          return toString(o[k]);
        }

        o[k] = '' + o[k];
      });

      return o;
    }

    console.log(toString(infected_dataINT));
    countriesObj = toString(infected_dataINT);
    // infected_data = toString(infected_dataINT);

    let ObjectConversion = Object.entries(countriesObj).map(entry => [CountryList[entry[0]], entry[1]]);
    infected_data = ObjectConversion;

    let script = document.createElement('script');
    script.src = 'js/myMapFile.js';
    document.head.appendChild(script);

  })


  // var infected_dataINT = getData();
  // var infected_data = infected_dataINT.toString();

The final output is infected_data

Answer №1

How to Create and Iterate Through a New Object:

var data = {
"Apple": 50,
"Banana": 30,
"Orange": 25,
"Grapes": 15,
"Pineapple": 10,
};

var descriptions = {
'Apple': 'A red fruit',
 'Banana': 'A yellow fruit',
 'Orange': 'A round orange fruit',
 'Grapes': 'Small and sweet fruit',
 'Pineapple': 'A tropical and spiky fruit',
};

var result = {};
Object.keys(data).forEach((item) => {
  var description = (descriptions[item] ? descriptions[item] : 'No description available');
  result[item.toLowerCase()] = { quantity: data[item], description: description };
});
console.log(result);

Answer №2

Let's say the primary dataset is referred to as countriesObj

const convertedResult = Object.entries(countriesObj).map(entry => [CountryList[entry[0]], entry[1]])

By executing the above code, a nested array will be generated. You can further convert this result to a regular array:

const finalResult = {}
convertedResult.map(entry=> { 
  finalResult[entry[0]] = entry[1] 
})

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

Why are the HTML links generated by JS not opening in Chrome?

<a href='http://www.xyz.hu/xyz' alt='Kosár' title='Kosár'>Megtekintés</a> Additionally: - A setInterval function refreshes the sibling's content every second, although it should not affect this specific el ...

Three.js experiences a memory leak issue

We are currently working on a single page app where users can switch between multiple Three.js apps. However, we have observed a continuous increase in memory usage by the tab. There is no memory leakage in our app and it appears that Three.js variables ar ...

The content within the iframe is not displayed

I've set up a dropdown menu with separate iframes for each option. Here's the code I used: $(function(){ $('#klanten-lijst').on('change',function(){ $('#klanten div').hide(); $('.klant-'+t ...

I believe I may not be properly managing dynamic memory destruction

I've been working on creating a dynamic array of student structures, but I'm running into a myriad of errors that I can't seem to fix. Despite my efforts to delete the memory I'm using, the compilation is still causing issues. The prog ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

Adding query parameters to the end of every link on a webpage

Wondering how to automatically add GET values to the end of each anchor href on a webpage? For instance, if you input google.com?label=12&id=12 I want to ensure that "?label=12&id=12" gets added to the end of every single href in an anchor tag on ...

Array offset is undefined even though it exists in the array

In my code, I am creating a MySQL connection array and passing it to a connect method like this: $database->connect(array(ROOT_DB_HOST, ROOT_DB_NAME, ROOT_DB_USERNAME, ROOT_DB_PASSWORD)); After using print_r() on the array inside the connect method, I ...

Rendering React.js components as children of DOM elements

Trying my hand at creating a custom Map component includes the task of designing a unique Map Annotation. Here's an example of how a MapAnnotation component appears in the render function: <MapAnnotation title='Annotation' latitude={ 12.3 ...

Easiest method for identifying repeated consecutive elements within an array

Given an array like the following: [1,5,3,3,4,4,4,5,6,6,6,6,8,9,1,1,5] In this array, the number '4' repeats continuously 3 times, while the number '6' repeats 4 times. The length of the array is not fixed. The task is to iterate thr ...

Google Maps Info Window with Asynchronous Loading

Need help with loading a Google map asynchronously on your website? Check out the code snippet below: function initialize(lat,lng) { var mapProp = { center: new google.maps.LatLng(lat,lng), zoom:15, mapTypeId: google.maps.MapTypeId.R ...

Whenever I adjust the layout of the navigation bar, the edges end up getting clipped

I'm having trouble with the border shape of my navbar. When I try to make it a rounded pill shape, the edges get cut off instead of being properly displayed. https://i.stack.imgur.com/sUN2Y.png Below is the HTML template: <template> <div cl ...

Exploring object manipulation and generating unique identifiers by combining values - a beginner's guide

After analyzing the provided data, my goal is to come up with a method of combining the IDs and returning an array of their corresponding keys. // example data var data = [ { id: 1, key: 'a' }, { id: 1, key: 'b' }, { id: 2, key ...

Receiving unexpected results when returning a function within a React hook

I'm currently working on developing a custom React hook that will provide users with a function to execute. This hook is designed to generate a function internally. Check out this simplified example // fetch.js import { useEffect, useState} from &qu ...

Master the art of animating ng-view transitions with AngularJS

I have 2 distinct HTML pages, namely welcome.html and login.html. These two pages are incorporated or "inserted" into a common page called index.html through the utilization of an exclusive attribute known as ngview, together with a router provider. This i ...

Display the output from the print_r function in PHP

Can anyone show me how to display the contents of this PHP array? I am a beginner and struggling with using print_r to echo the results. Thank you in advance. Below is the test result: Array ( [html_attributions] => Array ( ) [result] ...

In React, learn how to dynamically generate and return a specified number of HTML tags from a function based on the input number

In my React project, I am utilizing an icon library that includes both filled stars (FaStar) and empty stars (FaRegStar). I have written a function that takes a number between 1 and 5 as an argument, and based on this input, the function should return the ...

Issue with declaring array as variable in Postman

I am working on a POST request where the data is received in JSON format. I need to test it using the collection runner, but I'm facing an issue defining variables within an array. Here is a sample of the input data: Input Data: { "field1": "1", ...

Increasing the top padding of a resized iframe thanks to iframe-resizer

Currently, I am utilizing the remarkable iframe-resizer library to resize an iFrame while keeping it in focus. The challenge I am facing is my inability to figure out how to include additional padding at the top of the iFrame once it's resized. The ...

React Material Table - issue with data filtering accuracy

Currently in my React project, I am utilizing Material Table. While everything appears to be rendering correctly, the filtering and searching functionalities are not working as expected. To provide more context, below is a sample of the code: ht ...

Managing and enumerating array elements in an angular.js controller

In my Angular application, I am working with an array of objects that each contain a "ready" field storing a timestamp. My goal is to determine the count of objects where the "ready" timestamp is earlier than the current time. How can I achieve this? This ...