如何使用Typescript将数组映射到对象

时间:2018-11-06 13:10:30

标签: typescript

如何转换此数组:

['black', 'grey', 'dark grey'];

对此:

[ MyObject { name: 'black', description: 'colour is black' }, MyObject { ... } ]

3 个答案:

答案 0 :(得分:3)

第一个直接解决方案:定义一个接口Math.Ceiling,在这里创建一个新数组Colour,然后遍历旧数组将项目推入新数组:

colours

改为使用map

interface Colour {
  name: string;
  description: string;
};

const colours: Colour[] = [];

['black', 'grey', 'dark grey'].forEach((colour: string) => {
  colours.push({
    name: colour,
    description: `colour is ${colour}`
  });
});

答案 1 :(得分:3)

简单版本

['black', 'grey', 'dark grey'].map((color) => { return {name: color, description: `colour is ${color}`}});

最佳/更好的实践

interface Color {
  name: string;
  description: string;
}

type Colors = Color[];

const colors: string[] = ['black', 'grey', 'dark grey'];

colors.map((colour): Colors => ({ name: colour, description: `colour is ${colour}` }));

答案 2 :(得分:0)

另一种使用全局类型声明的直接方法(全局声明可帮助您在整个项目中的任何地方使用它),

declare global { // you can still define type without declaring it globally
  type Dictionary<T> = { [key: string]: T };
  type DefaultResponse = { 
    success: boolean,
    message: string,
  }
}

interface MyObject { 
    name: string,
    description: string 
  }

以及您的功能中

  var items = ['black', 'grey', 'dark grey']
  var results:[Dictionary<MyObject> | []]  = []

  items.reduce((result, field, index) => { 
    var _obj:Dictionary<string| any> =  { name: field , description : `The colour is ${field}` }
    results.push(_obj)
    return result;
  }, {})

  console.log(results)

在运动场中查看它: PlayGround

PS:如果您经常将其用于具有不同键的更多数组,这是更通用的解决方案:

 const destructureArray = (expectedKeys:any) => { 
    var aligned:[Dictionary<MyObject> | []]  = []
    var description = "The colour is "
    expectedKeys.reduce((param:any, field:any, index:any) => { 
        var _obj:Dictionary<string| any> =  {  name: field, description: `${description}: ${field}` }
        param = Object.assign(param, _obj)
        aligned.push(_obj)
       return param;
    }, {})
    return aligned;
   }

和函数调用

var expected = ['black', 'grey', 'dark grey']
var parsed = destructureArray( expected)
console.log(parsed)