Barin
Barin

Reputation: 33

Object to array in Angular

I need help with this code.

I working with "@angular/cli": "~12.0.5".

The createArray method receives an object and I want to transform the object to an array, but I have an error in 'userObj [key]'. I get the object (userObj) from Firebase through an http request and I can't change its structure.

This is the error message. -> 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 '{}'

Thanks!

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;
}

Upvotes: 0

Views: 455

Answers (2)

N.F.
N.F.

Reputation: 4184

Try this.

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

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

    for (const [key, object] of Object.entries(userObj)) {
        const user: UserModel = object as UserModel;
        user.id = key;
        users.push(user);
    }

    return users;
}

Upvotes: 1

Ernesto
Ernesto

Reputation: 4252

yow broh.

use 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)
}

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))

Upvotes: 0

Related Questions