skip to Main Content
let user: { id: number, name: string }[] = [
    { "id": 0, "name": "ABC" },
    { "id": 1, "name": "XYZ" }
];

let dataList: { id: number, name: string, address: string , pin: string, comment: string}[] = [];

If I want to move the user data array to dataList array how can I do that?

If I use map function then do I need to initialize empty data for other fields for dataList?

2

Answers


  1. Yes, I need to initialize empty data.

    Here is a simple example.

    let user: { id: number, name: string }[] = [
        { "id": 0, "name": "ABC" },
        { "id": 1, "name": "XYZ" }
    ];
    
    let dataList: { id: number, name: string, address: string, pin: string, comment: string }[] = user.map(item => {
        return {
            id: item.id,
            name: item.name,
            address: "",
            pin: "",
            comment: ""
        };
    });
    
    Login or Signup to reply.
  2. map return an array, so you simply

    dataList=user.map((x:any)=>({
      id:x.id,
      name:x.name,
      address:...
      ...rest of properties...
    })
    

    In "strict mode", if you don’t want add all the properties with a default value you should use some like

    dataList=user.map((x:any)=>({
      id:x.id,
      name:x.name,
      address:...
      ...not all the properties...
    } as { id: number, name: string, 
           address: string , pin: string, 
           comment: string})
    

    See the implicit convert "as". Generally you use an interface

    export interface dataModel
         { id: number, name: string, 
           address: string , pin: string, 
           comment: string}
         }
    
    dataList:dataModel=user.map((x:any)=>({
      id:x.id,
      name:x.name,
    } as dataModel)
    

    Yes, a "map" if "somelike"

    data=[]
    for (let i=0;i<user.length;i++)
       data.push({
           id:user[i].id
           name:user[i].name
       })
    return data
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search