Unable to populate an array with a JSON object using Angular framework

Here is the JSON object I have:

Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" }

This JSON data was retrieved as a response from an HTTP GET request using HttpClient in Angular.

Now, I want to populate this data into the following structure to display it as a dropdown list.

countryList: { countryCode: string; countryName :string }[];

I attempted the following code snippet :

for (const key in resData) {
  if (resData.hasOwnProperty(key)) {
     var obj ={
       countryCode :key,
       countryName : resData[key]
      }
    this.countryList.push(obj);
  }
}

However, upon execution, I'm encountering this error

"_this.countryList.push is not a function"

What could be the issue here?

Answer №1

In the code snippet you provided, the type of countryList is defined but it also needs to be initialized as an empty array before you can add elements to it. You can achieve this by adding the following line:

countryList: { countryCode: string; countryName: string }[] = [];

Answer №2

To retrieve entries from the data set and subsequently transform it into an array of objects, you can follow this method:

Object.entries(nations).map(([identifier, name]) => ({
    countryCode: identifier,
    countryName: name
}))

Answer №3

To properly store a list of countries, ensure that you declare countryList as an array.

var countryData = { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" };
countryList = [];
for (const key in countryData) {
  if (countryData.hasOwnProperty(key)) {
     var obj ={
       countryCode :key,
       countryName : countryData[key]
      }
    countryList.push(obj);
  }
}
console.log(countryList)

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

What is the best way to retrieve data from a jQuery AJAX call when it returns?

function isNewUsername(str){ var result; $.post('/api/isnewusername', {username:str}, function(data) { result = data.result; }, "json"); return result; } I am encounte ...

Decoding a JSON array API response in Golang: A step-by-step guide

I have been attempting to extract data from Wikipedia's API at https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/Smithsonian_Institution/daily/20160101/20170101 and convert it into an array of struc ...

Choosing values from an array using the IN statement

A database table in PostgreSQL contains an array field with various values: https://i.sstatic.net/HEjal.png I am attempting to retrieve all rows that have a matching id value in the field column. Below is the simplified query used (with table alias): SEL ...

Tips for iterating over an array that implements either of two interfaces in TypeScript

The objective is to develop a reusable method for filtering out items from an array that implements one of two interfaces Providing a code example would be most helpful: interface IDuration { start: number; end: number; } interface IRelativeDuration ...

Ways to update the UI dynamically in Angular without the need to refresh the entire page

On my page, I have multiple charts and I'm facing an issue where the chart UI does not update immediately when I try to make a delete call by clicking the delete button. I always have to refresh the browser to see the changes. I have provided the ful ...

Is there a way I can finish animating these divs in a diagonal motion?

I successfully made the blue and red divs move diagonally and switch positions. Now I am looking to achieve the same effect with the green and pink divs using a similar function. I am unsure about setting the position of both divs to 0 and 350 for those p ...

Using *ngFor to dynamically update the DOM when an array is modified via ngrx

Currently, I am utilizing *ngFor to present values from an array: [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' } ] In the html: <div *ngFor="let item of (items$ | async); trackBy: trackById;&quo ...

The error encountered is: "Unable to modify the 'x' property as it is readonly for the '[object Array]' object."

I've attempted various methods to modify this problem, regardless of how it's explained on different Stack Overflow threads. I am faced with an obstacle where I have an array composed of objects, and my goal is to iterate through the array and mo ...

Unable to execute app.get in Express framework of Node.js

const express = require('express'); let router = express.Router(); router.get('/create-new', (req, res, next) => { res.send('<form action="/submit-data" method="POST"><input type="text" name="name"><button ...

Issue: encountered an ECONNRESET error when attempting to read using the request module in mode.js

When attempting to download and parse large XML files from affiliate sites without a proper API, I encounter the same error consistently while using the request module for Node.js. Error: read ECONNRESET at exports._errnoException (util.js:746:11) at TCP. ...

The value of element.scrollTop is consistently zero

Why does the scrollTop position of an element always return 0? How can I correct this issue? JSFiddle var inner = document.getElementById('inner'); window.addEventListener('scroll', function() { console.log(inner.scrollTop); }) # ...

Tips on personalizing the vue-filemanager interface within Laravel

I'm currently utilizing the Laravel file manager package from here, which provides a pre-compiled JS file or allows for direct use of the vue-component through npm from here. Unfortunately, in both options, the front-end is not customizable. I have i ...

What causes RangeError: Maximum call stack size exceeded when Element UI event handlers are triggered?

I'm currently working on setting up a form and validating it with Element UI. Despite closely following the documentation, I am encountering an issue where clicking or typing into the input boxes triggers a RangeError: Maximum call stack size exceeded ...

Retrieve the chosen date from a DatePicker using a Javascript function

Is there a way to retrieve the user-selected date using a JS function? I attempted this method: var test = $("#datepicker").datepicker( 'getDate' ); However, when I display it with an alert, it shows [object object] instead of the date. This ...

Error [ERR_MODULE_NOT_FOUND]: Module could not be located in vscode

Issue with VS Code: Module Not Found Error View the image associated with the erroreN.png ...

A mistake occurred during the afterAll function, resulting in a TypeError: Unable to access properties of an undefined entity (specifically, trying to read '

While creating my spec file and settings, I encountered an error in the console: 'An error was thrown in afterAll TypeError: Cannot read properties of undefined (reading 'toLowerCase')', What could be causing this error to appear? H ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

Component in Next Js fails to pass props when using getInitialProps

I am facing some challenges with Next Js and could really use some assistance. We have a component where I am utilizing "getInitialProps" to pass props to it during the server-side rendering process. However, no matter what I try, the props do not seem to ...

Tips for wrapping text in a column within material-ui's DataGrid

Struggling to apply word wrap to my column header title in DataGrid from material-ui. I've attempted using sx and style with no success. I even tried this: const StyledDataGridtwo = styled(DataGrid)<DataGridProps>(({ theme }) => ({ root: { ...

Verification of three-dimensional password format with the use of AngularJS

I am trying to implement password validation in Angular.js that requires a combination of alphabetical, numerical, one upper case letter, one special character, no spaces, and a minimum length of 8 characters. How can I achieve this using Angular.js? Here ...