简体   繁体   English

在 typescript 中将 2 个不同类型的 object arrays 分配给彼此的最佳方法是什么?

[英]What is the best way for assigning 2 different type object arrays to eachother in typescript?

I want to assign 2 different type array to eachother attribute by attribute.我想按属性为每个属性分配 2 个不同类型的数组。 Can someone explain me what is the best way for this purpose?有人可以解释一下为此目的最好的方法是什么吗? I am using the code below, but when I have too much attribute, it does not good look.我正在使用下面的代码,但是当我有太多属性时,它看起来并不好看。 How can I map attributes easily?我怎样才能轻松获得 map 属性?

    export interface ClassA {
        Type: string;
        Name: string;
    }

    export interface ClassB {
        Typ: string; 
        Nm: string; 
    }



    let  items: ClassA[] = [
    { Type: 'T1', Name: 'N1'},
    { Type: 'T2', Name: 'N2'},
    { Type: 'T3', Name: 'N3'},
    ];

     
    let  items2:ClassB [] = [];


   items.forEach((item, index) => {
            let obj: ClassB  = {Typ:item.Type, Nm:item.Name };
            items2.push(obj);          
        });

console.log(items2);

Use map instead since you can map from one type to another type with it.请改用map ,因为您可以使用 map 从一种类型转换为另一种类型。 With explicit type annotations, it also gives you inference and typechecking in the map predicate as well:通过显式类型注释,它还可以在 map 谓词中进行推理和类型检查:

let items2: ClassB[] = items.map((item) => ({ Typ: item.Type, Nm: item.Name }));

Playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM