0

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;
}
1
  • What is the formate of your output array? Commented Jul 8, 2021 at 4:24

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @N.F, your code working for me. Thanks!
0

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

1 Comment

Hi @Ernesto thanks for sharing your code, but in each iteration the '' id '' must take the value for example of '' SJKLDFAD903 ".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.