Converting an object into an array using Angular

Can someone assist me with this code issue?

I am currently using

"@angular/cli": "~12.0.5"
.

The issue lies within the createArray method, where I need to convert an object into an array. However, I encounter an error specifically at 'userObj [key]'. The object (userObj) is retrieved from Firebase via an http request and its structure cannot be modified.

The error message reads as follows: -> Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.

Thank you for your help!

const userObj = {

   'SJKLDFAD903':{
      id: '',
      name: 'User 1'
   },
   'PLMKL-BAD89':{
      id: '',
      name: 'User 2'
   },
   'JHK34R-R903':{
      id: '',
      name: 'User 3'
   }
}

export class UserModel{
   id: string;
   name: string;
}

private createArray(userObj){ /*(userObj: object)*/
    const users: UserModel[] = [];

    if (userObj == null) { return []; }

    Object.keys(userObj).forEach(key => {
      
       const user: UserModel = userObj[key];
       user.id = key;

       users.push(user);
    });

    return users;
}

Answer №1

Give this a shot.

function convertObjectToArray(userInput){ /*(userInput: object)*/
    const usersList: UserModel[] = [];

    if (userInput == null) { return []; }

    for (const [key, obj] of Object.entries(userInput)) {
        const user: UserModel = obj as UserModel;
        user.id = key;
        usersList.push(user);
    }

    return usersList;
}

Answer №2

hey mate.

opt for Object.values instead

const userObj = {

   'SJKLDFAD903':{
      id: '',
      name: 'User 1'
   },
   'PLMKL-BAD89':{
      id: '',
      name: 'User 2'
   },
   'JHK34R-R903':{
      id: '',
      name: 'User 3'
   }
}

export class UserModel{
   id: string;
   name: string;
}

private createArray(userObj): UserModel[] {
    return Object.values(userObj)
}

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const userObj = {

   'SJKLDFAD903':{
      id: '',
      name: 'User 1'
   },
   'PLMKL-BAD89':{
      id: '',
      name: 'User 2'
   },
   'JHK34R-R903':{
      id: '',
      name: 'User 3'
   }
}

function createArray(userObj) {
    return Object.values(userObj)
}

console.log(createArray(userObj))

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 define a recursive object type in TypeScript specifically for managing CSS styles?

I have implemented React.CSSProperties to generate css variables, allowing me to define styles like let css: React.CSSProperties = { position: "relative", display: "inline-block", background: "red" } My goal is to build a theme with css variables ...

Shade within the autocomplete

Is there a way to make the color property warning work on my autocomplete element at all times, rather than just on focus? Any suggestions or workarounds? Check out this code sandbox for reference. I really want the warning color to be visible constantly ...

How can we wrap the Vuex store within a Vue plugin's install function?

I developed a plugin that utilizes Vuex for state management. // plugin.js import Vuex from "vuex"; import store from "./store.js"; export default { install(Vue, options) { const storeInstance = new Vuex.Store(store); Vue.pr ...

The jQuery selectors are not able to identify any dynamically generated HTML input elements

After successfully injecting HTML code into the DOM using Ajax, I encountered an issue where my jQuery selector was not working for a specific HTML input element. For example, when attempting to use the following jQuery code: $("input[id*='cb_Compare ...

Use Angular or Laravel to translate API response data before it is sent to the frontend

I am currently working with an Angular frontend and a Laravel backend. I have an API that returns color names in an array, which I need to translate based on the default language setting. In both my frontend and backend, I have two JSON files named en.json ...

The compilation time of Webpack and Angular 2

My compile time is currently at 40 seconds and I'm looking for ways to speed it up. I attempted setting the isolatedModules flag to true in the configuration but encountered an error: error TS1208: Cannot compile namespaces when the '--isolated ...

Unable to install local dependency using npm

After successfully using npm install react-financial-charts, I decided to include the package locally for specific reasons. I checked out the master branch of react-financial-charts from Github, resulting in two folders: C:\Users\user\projec ...

The installation of Clarity through the command 'ng add @clr/angular' does not succeed

Following the guidance in 'Chapter 3: Building an Issue Tracking System using Reactive Forms' from Angular Projects: Discover Angular 12 with 10 innovative projects and cutting-edge technologies, 2nd Ed. by Aristeidis Bampakos. This chapter&apos ...

What is causing the error to occur during the installation of the NestJS Client?

Encountered an error while attempting to install the nestjs client, and I'm completely puzzled by this issue. PS C:\Users\meuser> npm i -g @nestjs/cli npm ERR! code ETARGET npm ERR! notarget No matching version found for @angular- ...

Exploring Angular: How to access ViewChild from a dynamically loaded component

One of my components includes a ViewChild element like this: @ViewChild('overView') content: ElementRef; I am dynamically loading this component in the following way: let overviewComponent = this.vcr.createComponent(OverviewComponent); let conte ...

Streamlining a complex task in JavaScript

I am currently exploring options to streamline my code so that I don't need to repeat the same function 38 times. Instead, I would like to have a single function that can handle 38 different IDs separately. The script is designed to randomly select a ...

The code within $(document).ready() isn't fully prepared

Feeling frustrated after spending hours searching and attempting to refactor one of my old modules on a rendered Mustache template. It's like diving into code chaos. <section id="slideShow"> <script id="slideShow-template" type="text/tem ...

When the number of selected students exceeds zero, activate the collapsing feature in React

When the number of students exceeds zero, the collapse should automatically open and the text in Typography (viewStudentList) will display 'Close'. On the other hand, if the student count is zero, the collapse should be closed and the text on Typ ...

Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur: <!DOCTYPE html> <html> <head> <style type="text/css"> .errorcss { background-color: yellow; color:re ...

Ways to loop through HTML elements based on certain criteria?

Issue : The v-for loop is successfully iterating and binding data in the HTML template, but there is a challenge in partially iterating it based on certain conditions. Please refer to the JSFiddle link below for a demo. Objective : In the provided demo li ...

What steps should be taken to incorporate that dynamic sliding element (like a sliding screen paper) on the webpage?

When hovering over the leftmost part of the homepage at www.techants.com, a box shifts to the foreground. I examined the code and noticed a reference to something called screen paper. Does anyone know which script is being used for this effect? How can I ...

Utilizing a dynamic value in an Angular directive

For my latest project, I am working on developing a basic JSON pretty-printer directive using angular.js. Here is the code snippet I have so far: (function(_name) { function prettyJson() { return { restrict: 'E', ...

How to create an AngularJS Accordion with dynamic is-open attribute using ng-repeat

Even though I can get it to work without using ng-repeat, the issue arises when I have a list of elements and is-Open doesn't function properly. 1. It should only open one panel at a time (sometimes it opens all) 2. The value of is-Open should be ...

Troubleshooting issues with sending data from Node.js to MongoDB

I recently started learning nodeJS and I'm facing an issue with sending data from a register form to mongodb. It seems like I made a mistake while using the post method, as I am unable to see the data on postman. const express = require('express& ...

Encountering unproductive errors with custom editor extension in VS Code

I'm currently developing a custom vscode extension for a read-only editor. During testing, I encountered a rather unhelpful error message. Can anyone offer some insight on what might be causing this issue? 2022-11-25 11:36:17.198 [error] Activating ex ...