Home > other >  interface angular usage in for loop
interface angular usage in for loop

Time:06-16

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
export interface User {
    id: number;
    name: string;
    
}
@Component({
  selector: 'app-typeof-otcsection',
  templateUrl: './typeof-otcsection.component.html',
  styleUrls: ['./typeof-otcsection.component.css']
})
export class TypeofOTCSectionComponent implements OnInit {
user!: User[];
userList=any;
constructor() {}
ngOnInit(): void {
this.user={"id":0,"name":""}
}

let z=1
for (let k = 0; k < ((userarrayfromDB).length); k  ) {
let user =this.user 
user.id=z
user.name=userarrayfromDB[k].name
userList.push(user)
z  
}
}

So I am working on an angular project, I have made an interface called user, and using the interface I have made the object ie this.user . So suppose the userarrayfromDB length is 3 and when I am pushing the user object in userlist array , it is pushing the last array 3 times

for Example

[
    {
        "id": 3,
        "name": "nishit"
        
    }
],
[
    {
        "id": 3,
        "name": "nishit"
    }
],
[
    {
        "id": 3,
        "name": "nishit"
    }
]

I want the user list array like the below example

[
        {
            "id": 1,
            "name": "test"
            
        }
    ],
    [
        {
            "id": 2,
            "name": "test2"
        }
    ],
    [
        {
            "id": 3,
            "name": "nishit"
        }
    ]

CodePudding user response:

For this particular scenario, you don't necessarily need a for loop to move some data from one array to another. You could do it all in one line like this:

this.userList = [...userarrayfromDB];

In case your userarrayfromDB contains objects of a different shape (for example, they have more properties than you need), then you can use .map to project the data in the desired form:

this.userList = userarrayfromDB.map(user => {
  const result = { id: user.id, name: user.name };
  
  // conditionally assign more properties here.

  return result;
});

CodePudding user response:

let users = [[{"id":3,"name":"nishit"}],[{"id":3,"name":"nishit"}],[{"id":3,"name":"nishit"}]];
var  index=1;
var usersList = users.map(record =>{
  let user = record[0];
  user.id=index;
  user.name="test" index;
  index  ;
  return user;
  });
console.log(usersList)

  • Related