forming an instance from JSON information

In a .json file, I have data that includes information on countries such as their currency, major language, and land area in square kilometers or square miles.

{
    "countries": {
        "sweden": {
            "currency": "Swedish krona",
            "majorLanguage": "Swedish",
            "landArea": {               
                "value": 410330,
                "uom": "sq km"
                }           
            },
        "japan": {
            "currency": "yen",
            "majorLanguage": "Japanese",
            "landArea": {
                "value": 364500,
                "uom": "sq km"
                }           
            },
        "unitedStatesOfAmerica": {
            "currency": "US dollar",
            "majorLanguage": "English",
            "landArea": {
                "value": 3796742,
                "uom": "sq mi"
                }
            }
    }
}

I am looking for a way to dynamically create an object from this data structure that organizes the information by currency, major language, and land area for each country:

Object {
    "currency": Object {
    "japan": "yen",
    "sweden": "Swedish krona",
    "unitedStatesOfAmerica": "US dollar"
  },
  "majorLanguage": Object {
    "japan": "Japanese",
    "sweden": "Swedish",
    "unitedStatesOfAmerica": "English"
  },
  "landArea": Object {
    "japan": Object {
      "value": 364500,
      "uom": "sq km"
    },
    "sweden": Object {
      "value": 410330,
      "uom": "sq km"
    },
    "unitedStatesOfAmerica": Object {
      "value": 3796742,
      "uom": "sq mi"
    }
  }
}

The application consuming this data is built with Vue, so using JavaScript to achieve this objective is ideal. However, I aim to avoid relying on any third-party libraries. I am interested in a systematic approach that doesn't involve manually creating objects for currency, major language, and land area. I currently don't have a starting point for tackling this challenge and therefore do not have any initial code snippets to share.

Answer №1

Not too complicated:

const finalResult = {};

for (const countryName in countries) {
    const currentCountry = countries[countryName];
    for (const propertyKey in currentCountry) {
        if (!finalResult[propertyKey]) finalResult[propertyKey] = {};
        finalResult[propertyKey][countryName] = currentCountry[propertyKey];
    }
}

Answer №2

If you are looking to utilize the Array#reduce method, you can implement a solution similar to the following example.

const data = {"countries":{"sweden":{"currency":"Swedish krona","majorLanguage":"Swedish","landArea":{"value":410330,"uom":"sq km"}},"japan":{"currency":"yen","majorLanguage":"Japanese","landArea":{"value":364500,"uom":"sq km"}},"unitedStatesOfAmerica":{"currency":"US dollar","majorLanguage":"English","landArea":{"value":3796742,"uom":"sq mi"}}}};
            // iterate over countries object key value pair
const res = Object.entries(data.countries).reduce((obj, [country, valObj]) => {
  // iterate over the country value key-val pair
  Object.entries(valObj).forEach(([key, val]) => {
    // define key if not defined
    obj[key] = obj[key] || {};
    // define the value within object where key is country
    obj[key][country] = val;
  })
  return obj;
}, {})

console.log(res);

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

Can a single node_module folder be shared across multiple projects within a repository?

Imagine we have a central repository named REPO containing multiple grunt projects. Now, let's say we want to structure it like this: ROOT -- bower_components -- node_modules -- project_1 -- project_2 -- project_3 etc The current issue is that I nee ...

Challenges with iOS JSON Parsing and Data Formatting

Recently, I was working on a project that involved handling JSON data and encountered some difficulties in determining the best way to represent certain elements. Here is a snippet of the JSON structure I was dealing with: "phoneList": [ { "phoneRea ...

Issue arising from the lack of direct communication between parent and child elements

I am facing an issue with indirect communication in a react native application. The situation involves a parent component, implemented as a class component, and a child component, which is a functional component. Here is the Parent component: constructor ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...

Comparison of passwords in Nodejs is hindered by Bcryptjs

Struggling to compare passwords using bcryptjs for JWT authentication. Unable to successfully verify the password during login to sign the token and send it to the client. Issue The problem arises when trying to use the .compare() method in bcryptjs and ...

Make sure to verify a user's "clearance level" before entering a page

Recently delving into the world of node.js, I encountered a simple issue: In my routes file, there is a function that verifies if a user is authenticated. function isLoggedIn(req, res, next) { if(req.isAuthenticated()){ console.log(req.user); ...

"Problems arise with mongodb full $text search when sorting and filtering, causing duplicate items to

When using full-text search in my API and sorting by score, I am encountering an issue where the same item is returned multiple times. This behavior is not what I expected. How can I correct this to ensure unique results? Below is the structure of my rout ...

"After completing the task, the textview does not get updated in onpost

I am currently working on creating a movie catalogue app and facing an issue with the DetailActivity. The problem arises when I click on the first movie to view its details, then press the back button. Upon clicking on another movie, the app still displays ...

Guide to placing the cursor at a specified position within an editable content div

I am struggling with a div <div id="user_status" class="status expanddiv" onkeyup="username_Search('New','user_status');" contenteditable="true" data-text="What's on your mind?..."> Some Text will be inserted here. </div ...

Step-by-step guide to inserting an image into a Table Cell

I want to include my PDF image at the conclusion of the text in my table cell When it comes to my Table, I'm hoping that the image can be combined with the text seamlessly after it finishes <TableCell component="th" scope="row" className = {class ...

Come back and display JSX

I am encountering an issue with a function that is supposed to add JSX to the variable markup. However, when the function is called, the markup is displayed as plain text instead of JSX. How can I ensure that the string is rendered as JSX rather than plain ...

Add Firebase Data to Dropdown

Utilizing Vuetify to build a dropdown has been an interesting challenge for me. While I can successfully select a value and store it in the firebase database, I'm facing difficulties when it comes to repopulating the dropdown after page refresh. Belo ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

What is the best way to select the child of the second-to-last child?

In the structure of my HTML code, I have an unordered list with a class "menu" containing several list items and corresponding anchor tags like this <ul class="menu"> <li> <a href="#1"></a> </li> <div&g ...

Calculating the cost of a selected item from the Android dropdown menu

Utilizing the data retrieved from responseJson, I have successfully loaded it into a spinner in my application. Each item in the spinner contains different values, and my goal is to calculate the total value of all items using these individual values. In ...

Troubleshooting a JavaScript Error on an ASP.NET MasterPage

After implementing the following JavaScript code: <script type="text/javascript> $(document).ready(function () { $('#social-share').dcSocialShare({ buttons: 'twitter,facebook,linkedin,di ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

When you download a file through the unpkg CDN, the size of the npm package is

I am experiencing a discrepancy with the file size of a file in my npm package. The file is 307kb in size, but when I download it through unpkg, the same file is only 73.2Kb. I find it quite puzzling how the file can be smaller when downloaded over the net ...

Using a combination of different materials on a single mesh can lead to problems with z-index and clipping

Currently in my threejs project, I am attempting to apply two different materials to a mesh. One material has a solid color, while the other has a canvas texture. To achieve this, I have created both materials and added them to an array, which is then assi ...

Creating a bot that will only respond once when a user sends multiple photos simultaneously

I'm currently working on a Telegram bot using nodejs. I am utilizing the node-telegram-bot-api library and have implemented the on('photo') method to handle when a user sends a photo to my bot. However, I am facing an issue where if a user ...