Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file.

countryNew: {
IN: 159201 
BD: 82500
PK: 14237
UA: 486
RU: 9825
}

This needs to be transformed to...

countryNew: [ 
{countryCode: 'IN' , value : 159201}, 
{countryCode: 'BD' , value : 82500}, 
{countryCode: 'PK' , value : 14237}, 
{countryCode: 'UA' , value : 486}, 
{countryCode: 'RU' , value : 9825},
]

Answer №1

Converting objects to arrays is made simple by using the Object.keys() and Array.prototype.map() methods

const countries = {
  US: 300000,
  CA: 100000,
  MX: 50000,
  BR: 75000,
};

const convertedArray = Object.keys(countries)
  .map(key => ({ country: key, population: countries[key] }));

console.log(convertedArray);

Answer №2

To use Object.keys and Array.map efficiently, utilize the following structure:

const cities = Object.keys(cityData).map((city) => {
   return {cityCode: city, population: cityData[city]}
})

Answer №3

Consider utilizing the Object.entries method:

const countryInfo = {
  US: 3256,
  CA: 985,
  MX: 574,
  BR: 1028,
  AR: 437,
};

const output = Object.entries(countryInfo).map(item => ({countryCode: item[0] , population : item[1]}));

console.log(output);

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

I must develop a custom function that generates a pure JavaScript string with the 'name' index and includes all the 'props'

My code is almost correct, but instead of returning a ':' in the Json result as desired, it returns a ','. Is there a way to achieve the desired result without modifying the JSON string like I did with the "replaces"? I am searching fo ...

Develop a set of matching key/value pairs using TypeScript

Looking to develop a custom data type where InputKeys will serve as the keys, and the values will be key/value pairs. The keys should correspond to InputFieldKey, with the value being a string. My current progress includes {[key: string]: string}, but I n ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

Trouble arises when jquery's "position().top" clashes with the CSS3 property "transform: scale()"

Currently, I am working on adding a font resizer feature to my editing tool. To implement this, I made some changes to the text elements where their origin is now set to the bottom left corner. The normal version of the tool works perfectly fine, but when ...

Just ran $npm install and encountered an error message: "Module '../lib/utils/unsupported.js' not found."

Returning to work on a React project after switching from the Rails environment, I encountered an issue where I am unable to run NPM commands in my Mac terminal. Despite trying various solutions I found online, none seem to be effective. The real concern i ...

Prevent duplicate components from interacting with one another in Angular

My Tabs component has its own variables and functions, and it works perfectly. However, I encountered an issue when trying to place multiple tab components on the same page. Whenever I change the value of one tab, it also affects the other tab component. ...

I'm having trouble getting my code to work with axios in Vue.js. How can I fix this issue

I am trying to use axios.get to retrieve data from my database, but I encountered an error. Below is my code in store.js export default new Vuex.Store({ state: { test: null }, mutations: { testt(state, payload) { state.test = payloa ...

Leveraging the results from a static React function

I am currently working on a React + Webpack project that supports JavaScript ECMAScript 6. Here is the code snippet I am trying to implement: class ApiCalls extends React.Component{ static uploadFiles(files) { // upload code if(success) { ...

Error 403 with Google Search Console API: Access Denied

Currently, I am attempting to extract data from the GSC Search Analytics API using Python. Despite diligently following this resource, I have encountered an error that persists despite multiple attempts to remedy it: raise HttpError(resp, content, uri=se ...

Accurate linking to the interface while retrieving information from a specified URL

Just started with Angular and attempting to assign the returned json data to my interface, but it's not working as expected. Check out the code I'm using below: Stackblitz Json URL ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

Bootstrap's square-shaped columns

I would like to implement a grid of squares for navigation purposes. By squares, I mean that the colored areas should have equal width and height. Currently, I have achieved this using JavaScript, but I am interested in a CSS-only solution. My project is ...

How to retrieve the current route name or URL in AngularDart5

Exploring the OnActivate feature in Angular docs, I am attempting to utilize it to dynamically update the UI based on the current route. @Component( selector: "blah", template: """blah""", directives: const [routerDirectives]) class Blah ext ...

The system encountered an error while trying to access the file "/box/main.c" because it does not exist in the directory

Currently, I am working on a project that requires the use of judge0 API. Initially, everything was running smoothly when I utilized it with RapidAPI. However, I made the decision to switch to a self-hosted setup using a docker-compose.yml file. While my ...

Challenge with Sequelize Many-to-Many Query

Currently, I am facing an issue with connecting to an existing MySQL database using Sequelize in Node. The database consists of a products table, a categories table, and a categories_products table. My goal is to fetch products, where each product includes ...

Altering webpage content through the use of Ajax

I need a solution for dynamically updating web page content using JavaScript AJAX. One idea I had was to store different div layouts in separate files, like so: BasicDiv.div: <div> <p>Some Text</p> <button> A Button </ ...

Django DRF functions properly, however it returns an error when sending a response to an AJAX request

Successfully implemented an AJAX request using PUT in DRF. All functionalities are functioning correctly except for the error callback being triggered: DRF section: class ProductDataViewSet(viewsets.ViewSet): authentication_classes = [SessionAuthentic ...

Invoke a CoffeeScript function within a jQuery function

Two files are causing me trouble: one is written in plain jQuery, and the other is a Coffeescript The jQuery file looks like this: $(document).ready(function(){ checkPrice(); }); In comparison, the CoffeeScript file appears as follows: $ -> c ...

Exploring an Angular Real-World Example Application on Github - Resolving the Following Bug

my surroundings. export const environment = { production: false, api_url: 'localhost:3306/api' }; my personal server is at localhost:3306 (MAMP) The instructions provided are to edit src/environments/environment.ts in order to ch ...

Reveal the hidden div by sliding it up from the bottom

I have a container with brown branches resembling the image, and I'm looking to hide it. When a button is clicked, I want it to reveal from the bottom to the top, almost like it's being unmasked. I've ruled out a typical bottom-up slide anim ...