Converting a Multidimensional Object into an Array using Angular 8

How can I convert the data from LocalStorage into an array for *ngFor? The data is retrieved as a JSON object and after parsing it, I'm unsure how to change it into an array. Here's a sample of the object:

{
  "Monti": {
    "name": "Visa & MasterCard",
    "code": "monti",
    "deposit": "Free",
    "depositProcessing": "Instant",
    "icon": "<img src=\"//cdn.example.com/_payicons/monti.png\"/>",
    "supportWithdrawal": true,
    "withdrawAllowedWithoutDeposit": false,
    "depositLimits": {
      "currency": "EUR",
      "min": 10,
      "max": 5000
    }
  },
  "Montii": {
    "name": "Visa & MasterCard",
    "code": "monti",
    "deposit": "Free",
    "depositProcessing": "Instant",
    "icon": "<img src=\"//cdn.example.com/_payicons/monti.png\"/>",
    "supportWithdrawal": true,
    "withdrawAllowedWithoutDeposit": false,
    "depositLimits": {
      "currency": "EUR",
      "min": 10,
      "max": 5000
    }
  }
}

Answer №1

Within your data structure, there is an object containing two other objects. To transform this into an array of those objects, the format should resemble:

[
    {
        "name": "Visa & MasterCard",
        "code": "monti",
        "deposit": "Free",
        "depositProcessing": "Instant",
        "icon": "",
        "supportWithdrawal": true,
        "withdrawAllowedWithoutDeposit": false,
        "depositLimits": {
            "currency": "EUR",
            "min": 10,
            "max": 5000
        }
    },
    {
        "name": "Visa & MasterCard",
        "code": "monti",
        "deposit": "Free",
        "depositProcessing": "Instant",
        "icon": "",
        "supportWithdrawal": true,
        "withdrawAllowedWithoutDeposit": false,
        "depositLimits": {
            "currency": "EUR",
            "min": 10,
            "max": 5000
        }
    }
]

To achieve this, adjustments must be made when saving to the localStorage. If direct modification isn't feasible, a 'for in' loop can be utilized on the object to convert it into an array.

let arr = [];
for(let key in obj) {
  arr.push(obj[key]);
}

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

Reorganizing Execution Order in AfterViewInit with Subscriptions in Angular 10

In my component, I am using the ngAfterViewInit lifecycle hook to handle certain tasks: ngAfterViewInit() { this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0); this.subscription = this.dataService.dataChanged .subscribe( ...

Is there a way to retrieve all images within an Angular component, including images nested in child components and their sub-components?

I have experimented with various CSS selectors and methods, such as var elements = document.querySelectorAll('#container img'); var elements = this.el.nativeElement.querySelectorAll('img'); var elements = this.el.nativeElement.getElemen ...

What is causing the Ansible uri module to return a 400 error even when using correct credentials?

Our approach involves utilizing the uri module to access data from the Graylog API in JSON format. - name: Get data uri: url: http://graylog-host:9000/api/system url_username: username url_password: password force_basic_auth: yes retu ...

What is the best way to choose a specific row JSON based on its unique identifier

Looking for help with extracting bid or ask prices based on ID using Python. {"id":"141","bid":4.57000002,"ask":4.89999798},{"id":"345","bid":79933.93185001,"ask":92999.99999999} Any suggestions on how to extract the bid or ask price when given an ID? ...

When implementing useReducer with TypeScript, the error "Argument of type '(type, action) => { state: (...}' is not assignable to parameter of type 'ReducerWithoutAction<any>'" may occur

Recently, I decided to delve into learning TypeScript by building a simple shopping cart application. If you want to check out the code, feel free to visit my GitHub repository: https://github.com/CsarGomez/shopping-cart-reducers-tx I've encountered ...

Issue with ngOnInit not triggering upon opening dialog

Upon opening the dialog, the ngOnInit function is not triggered as expected. Strangely, the only way I am able to get it to fire is by resizing the window. I attempted to use detectChanges and zone.run() but unfortunately, it did not have any effect. Belo ...

Guide on verifying API response structure in Playwright with TypeScript

As a newcomer to Playwright, my focus is on writing API tests in TypeScript with an API response structured like this: { "id" : "abc123", "appCode" : "09000007", "applicationReference" : "ABCDEF& ...

Distinguishing between keydown.enter for textareas in Angular on mobile and desktop devices

As I work on developing a chat platform, one of the key features is the message input box using a textarea where users can type their messages. Currently, pressing the Enter key allows the user to send a message. However, I am curious to explore if it&apos ...

Unable to process GoogleMaps DirectionsResult Object for deserialization

Currently, I am facing an issue with the GoogleMaps API v3.0 where I am trying to store a DirectionsResult in my database and then retrieve it later for use on a map. The problem arises when I attempt to restore the saved object by extracting its JSON repr ...

Despite attempts to exclude them, types in node_modules continue to be compiled in TypeScript

During my attempt to compile my typescript source code, I've noticed that the compiler is also attempting to compile the types found within my node_modules directory. I am currently utilizing typescript version 2.6.1 and have my tsconfig file set up ...

Why is my root page not dynamic in Next.js 13?

I am currently working on a website using Next.js version 13.0. After running the next build command, I noticed that all pages are functioning properly except for the root page. The issue is that it's being generated as a static page instead of dynami ...

Issue with Yarn and Webpack: Unable to locate module 'contextify' in Node

My current challenge involves running an app (which I am currently working on) by executing the command: yarn start However, upon trying to run the app, I encountered the following error message: ts-node ./src/engine/server/server Error: Cannot find mod ...

What is the best way to limit input to only numbers and special characters?

Here is the code snippet I am working with: <input style="text-align: right;font-size: 12px;" class='input' (keyup.enter)="sumTotal($event)" type="text" [ngModel]="field.value" (focusin)="focusin()" (focusout)="format()" (keyup.ente ...

What is the purpose of using two forward slashes before a JSON string?

I am struggling with a JSON string I retrieved from Google. The issue lies in the presence of double slashes at the beginning of the JSON string, causing it to throw a JSON exception when I try to use it. Is there a way for me to properly escape these cha ...

What is the process by which TypeScript verifies validity when type assertions are made in TypeScript?

Currently, I am diving into the concept of type assertion in typescript. Despite going through various resources like the official documentation, an older version, and other articles such as this one, I still find myself puzzled about how typescript valida ...

Incorporating CCPoint into CCArray

In my quest to select a random CCPoint from the CCArray, and subsequently exclude that point to avoid duplication, I encountered an issue with the following code snippet: myArray->addObject(pos1); In this scenario, pos1 denotes a CCPoint, while my ...

W/System.err: The data in the form of an empty array cannot be converted into a JSONObject due to a org.json.JSONException

Currently, I am working on saving data in a MySQL database. The code snippet for this task is as follows: private void uploadMultipart(final String imageData,final String titolo,final String sottotitolo,final String data) { String tag_string_req ...

Encountering a 'System.IO.FileLoadException' when using newtonsoft-json

When I try to use the toJSONString() method in my dll assembly in Visual Studio, the debugger keeps throwing a 'System.IO.FileLoadException' error in the output window. I included the newtonsoft-json.dll library via NuGet, so it's puzzling w ...

What is the best way to integrate node.js with HTML?

I am currently utilizing node.js to interact with an API on the IBM Cloud platform. I have successfully accessed the response in my code, but now I need to pass this data to an HTML page using "res.send". How can I achieve this? Below is the Node.js code ...

Analyzing dates and compiling a count using JavaScript

In my current project, I am faced with the challenge of comparing dates stored in the format 'Y-M-D H-i-s' within an array to eliminate duplicates and keep a count alongside the original date. The method I am using to compare the dates is shown b ...