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;
}
Alireza Ahmadi
10.2k8 gold badges28 silver badges66 bronze badges
asked Jul 8, 2021 at 2:23
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;
}
answered Jul 8, 2021 at 4:25
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))
answered Jul 8, 2021 at 4:20

1 Comment

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.