Converting Object to Array of Objects in Typescript

Looking to convert an object into an array of objects in order to use the angular2 *ngFor directive. Here is the initial JSON object:

Object {CountryID: 87944818, ISO2: "do", ISO3: "u", Name: "aliqua sit magna tempor"} 

The desired format is an array of objects like this:

[Object]
     0: Object
       CountryID: 87944818
       ISO2: "do"
       ISO3: "u"
       Name: "aliqua sit magna tempor"

I attempted to achieve this using Object.keys and map but did not get the expected output. Here is what I tried:

let keys:any[] = [];
        for (let key in value) {
            console.log(key);
            keys.push({key: value[key]});
        }
        console.log(keys);

The 'value' variable represents the object that needs to be converted.

Answer №1

Instead of creating a new array and pushing the object into it, why not just have an array already defined?

let myObj = {CountryID: 87944818, ISO2: "do", ISO3: "u", Name: "aliqua sit magna tempor"}
let myArr = [];
myArr.push(myObj);
console.log(myArr);

Edit:

An alternative approach could be:

myArr = [myObj]

Answer №2

keys.push({[key]: value[key]});

It is important to note that the value of the key should be set, not just the key itself.

The keys available will include:

[
  {CountryID: 87944818},
  {ISO2: "do"},
  {ISO3: "u"},
  {Name: "aliqua sit magna tempor"},
]

I am unsure of the usefulness of this information...

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 strategies can I use to streamline this array update function code?

Looking to simplify my updated array function. The update function involves updating and comparing values in an array. The comparison will be done within the fruit_temp. For example, data in fruit_temp's fruit_db_id corresponds to an existing id in th ...

There are occasional instances of phone skipping functions within a loop in Ionic 4

My POS app is designed to work with a thermal printer using the Bluetooth Serial plugin. The issue I am facing is that when the order is too long, I divide the invoice into 300-bit chunks. This process works flawlessly on my phone every time, but when I at ...

Node.js expressing caution about the use of backslashes in console logging statements

While this issue may not be considered crucial, I have observed an unexpected behavior when it comes to logging backslashes to the console. To verify the results, please try the following two examples in your terminal. I experimented with versions 0.10 an ...

Prevent browser sync from mirroring Angular 2 changes

I have recently started working on an Angular 2 project using a template that does not involve gulp or webpack. I am facing an issue where any action I perform on one browser seems to be mirrored across multiple browsers on different computers. This behavi ...

Can I display different text when blinking with Javascript?

I need to display text that changes every few seconds within a single div. var blink_speed = 1000; // every 1000 == 1 second, adjust to suit var t = setInterval(function () { var ele = document.getElementById('myBlinkin ...

Tips for limiting the maximum number of characters in CkEditor 5 for react js

Is there a way to limit the amount of characters in a CKEditor textarea in a React JS environment? I'm trying to set a maximum character count for the text area in CKEditor Does anyone have any examples or suggestions on how to achieve this? retur ...

How can you dynamically disable the submit button on a form in Angular 7+ based on the form's current status?

Let's consider a scenario with a button in our code: <button type="button" class="menu-button" [disabled]="isInvalidForm()">Save</button isInvalidForm() { console.log('I am running!'); return this.nameValidator.errors || this.last ...

Selection box and interactive buttons similar to those found in Gmail

Looking to achieve these effects for <option> and <button> using CSS and JavaScript. Any suggestions on how to do this? ...

Changing the bootstrap popover location

I'm looking to customize the position of a Bootstrap popover that appears outside of a panel. Here's my setup: HTML: <div class="panel"> <div class="panel-body"> <input type="text" id="text_input" data-toggle="popover ...

Handlers for mouseover, mouseout, and click events are failing to trigger

Take a look at this code snippet - setEvents:function(a, b){ if(b) { $('#id').mouseover(function(){ console.log('mouse over') }) $('#id').mouseout(function(){ console.l ...

Adjustable slider to display progress, with the ability to reach full completion and reset back

In my current project, I am working on a progress bar that is linked to XP and MAX XP values in SQL. Each time a button is clicked, the user receives 1 XP and the maximum XP is set at 10. Ideally, when a user reaches 100% XP, the progress bar should reset ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

Converting Geometry into BufferGeometry

From my understanding, Geometry contains a javascript object structure of the vertices and faces, while BufferGeometry stores raw WebGL data using Float32Arrays, etc. Is there a method to convert regular Geometry into BufferGeometry, which is more memory ...

Having difficulty duplicating a button with a click event using jQuery

I have implemented a button that reveals a phone number when clicked using the code below: var shortNumber = $("#phone_ch").text().substring(0, $("#phone_ch").text().length - 12); var onClickInfo = "_gaq.push(['_trackEvent', 'EVENT-CATEGOR ...

Choose or unselect checkboxes that are currently visible

I am working on an accordion feature that includes checkboxes for each item. Some of the accordion items are initially hidden using the style="display:none;" attribute. Take a look at the HTML DOM hierarchy in this screenshot: https://i.sstatic.net/Za8Ly ...

Utilizing Google Places Autocomplete to tailor search outcomes

I'm currently working on customizing the output of my Google Places autocomplete code. Specifically, I want to change the displayed result when a user selects an address from the list. For example, one of the results is: '45 Alexandra Road Holi ...

Automatically generate user clicks within primeng pagination

I am implementing primeng's p-dataview component with pagination to display user test questions. <p-dataView [value]="userTestQuestions" [paginator]="true" [rows]="1" [totalRecords]="totalTestQuestions"> <ng-template let-question pTempl ...

Guidelines on incorporating several JavaScript functions with variables in a single file

Having some trouble figuring out how to incorporate multiple functions with variables in a single JavaScript file. The syntax is throwing me off. I'm attempting to follow an example from randomsnippets.com but would like to expand it to allow for add ...

The Angular FormControl data does not reflect changes made in the view

Currently, I am facing an issue with reading data from a FormGroup using ReactiveFormsModule in Angular. Despite my efforts, the form fields always return empty values. I have set up a route that loads a submodule called 'ByHModule,' which conta ...

Importing dynamically divides the code without implementing lazy loading

I am exploring the implementation of lazy loading in Vue Router to ensure that certain parts of the code are only loaded when they are needed. Following the guidelines from the official documentation on Lazy Loading in Vue Router available at: https://rou ...